加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用AngularJS超时

发布时间:2020-12-17 07:58:19 所属栏目:安全 来源:网络整理
导读:我是AngularJS的新手.我目前正在查看$timeout服务.我知道它就像是setTimeout函数的包装器.文档说它提供了异常处理.此外,文档说我可以取消并刷新超时. 当超时发生异常时,有人可以向我解释一下吗?我也不明白为什么我需要刷新超时.我想要一个解释或者也许是一
我是AngularJS的新手.我目前正在查看$timeout服务.我知道它就像是setTimeout函数的包装器.文档说它提供了异常处理.此外,文档说我可以取消并刷新超时.

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

更新:
当我尝试运行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
 });

阅读所有关于承诺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;
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读