以下是我正在尝试做的事情。当第一个超时被强制取消时,我想启动第二个超时功能,没有已经存在的延迟,没有取消超时。
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
$scope.data2_timeout = $timeout(function() {
// some action
}, 4000);
$scope.show = function() {
if (some action) {
$timeout.cancel($scope.data1_timeout); //works perfectly fine
//But how do I update data2_timeout so that the action inside it occurs just after data1_timeout is cancelled in this block.
}
}
答案 0 :(得分:1)
通过取消$timeout
&#39}轻松完成并手动调用您的功能。保持简单=)。
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
$scope.data2_timeout = $timeout(function() {
myAction();
}, 4000);
$scope.show = function() {
if (some action) {
$timeout.cancel($scope.data1_timeout);
$timeout.cancel($scope.data2_timeout);
myAction();
}
}
function myAction () {
console.log('done');
}
答案 1 :(得分:0)
这使用$timeout
返回的承诺,$timeout
取消后会被拒绝。 catch处理程序拒绝第二个计时器并立即执行其操作。
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
$scope.data2_timeout = $timeout(function() {
// some action
}, 4000);
$scope.data1_timeout.catch(function(){
$timeout.cancel($scope.data2_timeout);
//same actions here as in data2_timeout
})
将data2_timeout功能封装在命名函数中并从两个地方调用它更有意义:
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
function someAction2() {
//some action
}
$scope.data2_timeout = $timeout(someAction2, 4000);
$scope.data1_timeout.catch(function(){
$timeout.cancel($scope.data2_timeout);
someAction2();
})
注意:如果意图是data2操作等待data1_timeout完成或取消,那么不要将data2作为超时添加,而只需将其添加为data1_timeout promise的.finally()
回调。
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
$scope.data1_timeout.finally(function() {
// do data2 stuff here.
// Guaranteed to run, after data1_timeout completes or is canceled.
});