Javascript 停止附加承诺的$interval函数
在一个角度控制器内,我试图停止一个间隔。如果有一个.那么.的承诺链接到它,是否不可能停止间隔 为什么stopCount函数在这里工作Javascript 停止附加承诺的$interval函数,javascript,angularjs,setinterval,Javascript,Angularjs,Setinterval,在一个角度控制器内,我试图停止一个间隔。如果有一个.那么.的承诺链接到它,是否不可能停止间隔 为什么stopCount函数在这里工作 var stop = $interval(function(){ console.log('testing interval'); }, 1000); $scope.stopCount = function(){ $interval.cancel(stop); } 但不是在这里,然后呢 var stop = $interval(function
var stop = $interval(function(){
console.log('testing interval');
}, 1000);
$scope.stopCount = function(){
$interval.cancel(stop);
}
但不是在这里,然后呢
var stop = $interval(function(){
console.log('testing interval');
}, 1000)
.then(function(){
console.log('complete')
});
$scope.stopCount = function(){
$interval.cancel(stop);
}
提前谢谢 好吧,那么你显然不完全理解承诺。。。这项工作的原因是:
var stop = $interval(function(){
console.log('testing interval');
}, 1000)
.then(function(){
console.log('complete')
});
$scope.stopCount = function(){
$interval.cancel(stop);
}
因为你有两个承诺。。。第一个是毫秒,即1000/1秒。另一个是.then()承诺。你不能在一个功能中使用两个承诺
如果您看到文档,您会看到$interval的语法是:
$interval(fn,延迟,[count],[invokeApply],[Pass])
对于cancel函数,这是语法
$interval.cancel([promise]);
试试这个
// The problem is that stop is not storing the promise of $interval
// It's storing the promise returned by the .then method
var stop = $interval(function(){
console.log('testing interval');
}, 1000)
.then(function(){
console.log('complete')
});
$scope.stopCount = function(){
$interval.cancel(stop);
}
// Try this
// Now stop is using $intervals promise,
// not .then. We'll call .then separately below
var stop = $interval(function(){
console.log('testing interval');
}, 1000);
// Now we can cancel the 'stop' interval below
// This promise has to have a success callback
// AND an error callback.
stop.then(function(){
console.log('complete')
}, function(err) {
console.log('Uh oh, error!', err);
});
$scope.stopCount = function(){
$interval.cancel(stop);
}
检查这个$timeout将返回一个您可以调用的承诺。然后继续,因为在某种意义上它就像一个承诺。它会在一定时间后做一些事情。虽然时间间隔不同,但它仍在继续。因此,一旦启动它,您唯一能做的就是停止它如果您想在1秒后执行console.log,那么只需插入$timeout而不是$interval,所有这些都应该可以工作:)谢谢您的解释!那么,在间隔被取消后,没有办法运行函数了吗?想想这个。.then方法返回一个新的承诺。因此,您正在尝试停止新的proimse,而不是原来的proimse。如何将$interval作为毫秒的承诺?你只能取消它。另一方面,您完全可以对同一承诺使用多个回调。除非我误解了你的意思,否则我不是在说对同一个承诺的多次回调。我说了很多承诺@这部分是完全正确的。我还是不明白有两个承诺$interval返回一个承诺,这是代码中唯一的承诺$interval返回一个承诺(.then),就是这样吗?有什么我看不到的吗?我想我理解你的意思,写下我自己的答案澄清了这一点:)尽管在一个函数中使用两个承诺的部分非常混乱。这是真的,但不是OP的代码发生了什么。我想你的意思是,你不能在同一个变量中存储两个承诺:)它确实会停止间隔,但我没有看到在我停止时记录“完成”。嗯,这就是$timeout和$interval之间的区别$interval应该在interval的每次迭代中调用一个console.log$timeout只会在完成后调用你的console.log。听起来你甚至都没有得到它。这段代码的结果应该是每秒记录一次“complete”。我确实每秒记录一次测试间隔,但不是complete?它们都应该被记录,首先测试,然后完成。在每次迭代中