【问题标题】:Using an AngularJS timeout使用 AngularJS 超时
【发布时间】:2013-12-20 08:22:29
【问题描述】:

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

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

更新: 当我尝试运行停止函数时,与 myTimer get 关联的 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; 
}  

谢谢!

【问题讨论】:

    标签: angularjs timeout


    【解决方案1】:

    $timeout 确实是最棒的。

    异常处理

    $timeout 返回一个可以有错误状态的承诺。例如

     var timePromise = $timeout(function(){ 
        throw new Error('I messed up');
     }, 10000);
    
     timePromise.catch(function(err){
        // do something with the error
     });
    

    阅读所有关于 Promise 的内容here.


    取消

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

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

    【讨论】:

    • 感谢您的反馈。我一直在玩这个,但我仍然遇到问题。如果我的控制器中有一种方法可以创建计时器,而另一种方法可以停止计时器,则会引发异常。为什么?
    • 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("时钟发生错误。"); }); }} $scope.stopClock = function () { $timeout.cancel(myTimer); $scope.isClockActive = false; }
    • 我很困惑,你为什么把这段代码作为评论发布?这是什么意思?猪肉?
    • 我更新了问题以更好地格式化代码。本质上,我仍然不了解异常处理部分。如果我尝试取消正在运行的计时器,为什么会抛出异常?它不应该停止吗?
    • 它将被停止。但是,假设您编写了其他人正在使用的代码。他们可能不知道promise 来自计时器。如果该承诺未解决,它将catch,并且取消的计时器将无法解决。
    猜你喜欢
    • 1970-01-01
    • 2014-06-15
    • 2016-01-12
    • 1970-01-01
    • 2017-08-07
    • 2015-06-21
    • 2019-07-07
    • 2017-10-06
    • 2015-08-15
    相关资源
    最近更新 更多