我是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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Fre*_*all 11
$timeout 确实是最棒的.
$timeout返回一个可能有错误状态的promise.例如
var timePromise = $timeout(function(){
throw new Error('I messed up');
}, 10000);
timePromise.catch(function(err){
// do something with the error
});
Run Code Online (Sandbox Code Playgroud)
取消a $timeout很容易.而不是使用clearTimeout你传递承诺.
var timePromise = $timeout(function(){
// do thing
}, 23432);
// wait I didn't mean it!
$timeout.cancel(timePromise);
Run Code Online (Sandbox Code Playgroud)
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!
Run Code Online (Sandbox Code Playgroud)
或者这个文件:
var itsDone = false;
$timeout(function(){
itsDone = true;
}, 5000);
Run Code Online (Sandbox Code Playgroud)
通过这个测试:
// 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;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6043 次 |
| 最近记录: |