javascript - 停止带有 promise 的 $interval 函数

标签 javascript angularjs setinterval

在 Angular Controller 内部,我试图停止一个间隔。如果有一个 .then promise 链接到它,是否不可能停止间隔?

为什么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);
}

提前致谢!

最佳答案

试试这个!

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

关于javascript - 停止带有 promise 的 $interval 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35446282/

相关文章:

javascript - Angular.JS - 事件被多次触发

javascript - 将 youtube iframe 放在另一个带有图标关闭的框架上

javascript - 两个 AngularJS 服务之间的消息传递

javascript - 使用 $.each 和 setInterval 循环播放连续动画?

javascript - jQuery自动点击功能

javascript - Babel 和 Browserify/Webpack 混淆

javascript - bs-select 加载以前的数据 - AngularJS

javascript - Angular - 指令不起作用

javascript - 个人最佳记分员/计时器

javascript - 为什么 setInterval() 在此代码中停止得太早?