使用AngularJS超时 [英] Using an AngularJS timeout

查看:67
本文介绍了使用AngularJS超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是AngularJS的新手.我目前正在查看$ timeout服务.我知道这就像setTimeout函数的包装器.该文档说,它提供了异常处理.另外,文档说我可以取消并刷新超时.

I'm new to AngularJS. I'm currently looking at the $timeout service. I understand that it's like a wrapper for the setTimeout function. The documentation says that it provides exception handling. In addition, the documentation says I can cancel and flush a timeout.

有人可以在超时发生异常时向我解释吗?我也不明白为什么我需要刷新超时.我希望提供一个解释或一个jsfiddle.对于我的一生,我无法弄清楚为什么或什至如何使用这些附加功能.

Can someone please explain to me when an exception would happen with a timeout? I also don't understand why I need to flush a timeout. I would love an explanation or maybe a jsfiddle. For the life of me, I can't figure out why or even how to use these additional features.

更新: 当我尝试运行stop函数时,抛出了与myTimer相关的catch处理程序.这是我的代码:

Update: When I attempt to run the stop function, the catch handler associated with myTimer get's thrown. Here is my code:

var myTimer = null; 
$scope.hasStarted = false; 
$scope.start = function () { 
  if ($scope.hasStarted === false) { 
    $scope.isTimerActive = true; 
    myTimer = $timeout(function () { $scope.isTimerActive = false; }, 5000); 
    myTimer.catch(function (err) { 
      alert("An error happened with the clock."); 
    }); 
  }
} 

$scope.stopClock = function () { 
  $timeout.cancel(myTimer); 
  $scope.isClockActive = false; 
}  

谢谢!

推荐答案

$timeout确实是最出色的.

$timeout返回一个可能具有错误状态的promise.例如

$timeout returns a promise which can have an error state. For example

 var timePromise = $timeout(function(){ 
    throw new Error('I messed up');
 }, 10000);

 timePromise.catch(function(err){
    // do something with the error
 });

此处查看所有有关承诺的信息.

取消$timeout很容易.不用使用clearTimeout,而是将承诺传递回去.

Canceling a $timeout is easy. Instead of using clearTimeout you pass the promise back.

 var timePromise = $timeout(function(){
     // do thing
 }, 23432);

 // wait I didn't mean it!
 $timeout.cancel(timePromise);


冲洗

Flush对于单元测试最有用,最终它会触发所有未完成的回调.


Flush

Flush is most useful for unit testing, ultimately it fires any outstanding callbacks.

$timeout(function(){
   console.log('$timeout flush');
}, 222);

$timeout(function(){
   console.log('rocks my face');
}, 234232);

$timeout.flush(); // both console logs will fire right away!

或此文件:

var itsDone = false;
$timeout(function(){
   itsDone = true;
}, 5000);

通过此测试:

// 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;
});

这篇关于使用AngularJS超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆