1

以下是我正在尝试做的事情。当第一次超时被强制取消时,我想启动第二次超时功能,没有已经存在的滞后,没有取消超时。

$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.
  }
}

4

2 回答 2

1

通过取消两者$timeout并手动调用您的函数来轻松完成。保持简单=)。

$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');
}
于 2017-08-28T16:31:56.097 回答
0

这使用了当被取消$timeout时被拒绝的承诺。$timeoutcatch 处理程序拒绝第二个计时器并立即执行其操作。

$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 设置为超时,只需将其添加.finally()为 data1_timeout 承诺的回调即可。

$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.
});
于 2017-08-28T16:49:52.353 回答