停止带有 promise 的 $interval 函数

Stopping an $interval function with a promise attached

在 angular 控制器内部,我正在尝试停止间隔。如果有 .then 承诺链接到它,是否无法停止间隔?

为什么stopCount函数在这里起作用

var stop = $interval(function(){
    console.log('testing interval');
  }, 1000);

$scope.stopCount = function(){
  $interval.cancel(stop);
}

但这里没有 .then

var stop = $interval(function(){
    console.log('testing interval');
  }, 1000)
  .then(function(){
     console.log('complete')
  });

$scope.stopCount = function(){
  $interval.cancel(stop);
}

提前致谢!

好吧,你显然没有完全理解 promises...这个 dosen 工作的原因:

var stop = $interval(function(){
    console.log('testing interval');
  }, 1000)
  .then(function(){
     console.log('complete')
  });

$scope.stopCount = function(){
  $interval.cancel(stop);
}

是因为你有两个承诺...第一个是毫秒,即1000/ 1second。另一个是 .then() 承诺。你不能在一个函数中使用两个承诺。

如果您查看文档 here 您会看到 $interval 的语法是:

$interval(fn, delay, [count], [invokeApply], [Pass]);

对于取消函数,这是语法

$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);
}