我是AngularJS的新手.我目前正在查看$timeout服务.我知道它就像是setTimeout函数的包装器.文档说它提供了异常处理.此外,文档说我可以取消并刷新超时.
当超时发生异常时,有人可以向我解释一下吗?我也不明白为什么我需要刷新超时.我想要一个解释或者也许是一个小伙子.对于我的生活,我无法弄清楚为什么甚至如何使用这些附加功能.
更新:
当我尝试运行stop函数时,抛出了与myTimer相关的catch处理程序.这是我的代码:
谢谢!
$timeout确实非常棒.
异常处理
$timeout返回一个可能有错误状态的promise.例如
@H_502_6@var timePromise = $timeout(function(){ throw new Error('I messed up'); },10000); timePromise.catch(function(err){ // do something with the error });阅读所有关于承诺here.
取消
取消$timeout非常简单.而不是使用clearTimeout,您将回传承诺.
@H_502_6@var timePromise = $timeout(function(){ // do thing },23432); // wait I didn't mean it! $timeout.cancel(timePromise);红晕
Flush对于单元测试最有用,最终会触发任何未完成的回调.
@H_502_6@$timeout(function(){ console.log('$timeout flush'); },222); $timeout(function(){ console.log('rocks my face'); },234232); $timeout.flush(); // both console logs will fire right away!或者这个文件:
@H_502_6@var itsDone = false; $timeout(function(){ itsDone = true; },5000);通过这个测试:
@H_502_6@// old no flush way (async) it('should be done',function(done){ expect(isDone).to.be.false; setTimeout(function(){ expect(isDone).to.be.true; done(); },5001); }); // now with flush it('should be done',function(){ expect(isDone).to.be.false; $timeout.flush(); expect(isDone).to.be.true; });