我是 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/