angularjs - 使用 AngularJS 超时

标签 angularjs timeout

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

有人可以向我解释什么时候超时会发生异常吗?我也不明白为什么我需要刷新超时。我想要一个解释或者一个 jsfiddle。对于我的生活,我无法弄清楚为什么甚至如何使用这些附加功能。

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

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 。例如

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

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

阅读所有关于 promise 的信息 here.

取消

取消 $timeout简单。而不是使用 clearTimeout你把 promise 传回去。
 var timePromise = $timeout(function(){
     // do thing
 }, 23432);

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

冲洗

Flush 对单元测试最有用,它最终会触发任何未完成的回调。
$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 - 使用 AngularJS 超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20365361/

相关文章:

javascript - VS Code 未完成 $routeProvider

angularjs - 使用哪一个,AngularUI Bootstrap 还是 AngularStrap?

javascript - 路由防护中的 Angular 2 对话框可以停用

java - Weblogic 10 上的 EJB3 - 首次访问数据库时超时

PHP超时错误处理

javascript - TypeError : cannot read property . 然后是未定义的

google-apps-script - 如何在 Google Apps Script 提供的 HTML 站点中使用 Angular.js?

Android HttpPost 请求超时

java - 如何在 Java 中设置 Windows 通知图标出现的时间长度

delphi - 用Delphi实现读取文件时的超时