在附加了承诺的情况下停止$ interval函数

时间:2016-02-17 01:26:05

标签: javascript angularjs setinterval

角度控制器内部我试图阻止间隔。如果有一个.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);
}

提前致谢!

2 个答案:

答案 0 :(得分:1)

好的,所以你显然不完全理解承诺......这个代理工作的原因:

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

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

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

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

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

对于取消功能,这是语法

$interval.cancel([promise]);

答案 1 :(得分:1)

试试这个!

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