在使用 Angular 计时器满足条件后,使用 promise 取消 $interval
Cancelling $interval with promise after condition is met with Angular timer
我很难取消我的 $interval 服务。我不完全确定我错过了什么。
我已经初始化了一个正在倒数的计数器 属性。 $scope.sessionCounter
$scope.sessionCounter = 5;
var intializeSessionCounter = function () {
$scope.sessionTime();
$interval(function () {
$scope.sessionCounter--;
if ($scope.sessionCounter > 1) {
console.log('timedown', $scope.sessionCounter);
}
else {
$scope.showSessionTimeoutWarningModal();
$scope.stop();
}
}, 1000);
}
intializeSessionCounter();
上面的一切都在通过 if 语句时工作正常。当 $scope.sessionCounter 转到 1 时,我点击了 else 语句。弹出我要打开的模式。 Next $scope.stop 被命中并且 $interval.cancel(null) 被读取。但是,没有任何取消,我的模式继续重新打开,因为 $interval 继续 运行 为负数。
$scope.stop = function () {
$interval.cancel(null);
}
您必须将 $interval 提供程序绑定到某个变量。
试试这个:
$scope.sessionCounter = 5;
var intializeSessionCounter = function () {
$scope.sessionTime();
$scope.interval = $interval(function () {
$scope.sessionCounter--;
if ($scope.sessionCounter > 1) {
console.log('timedown', $scope.sessionCounter);
}
else {
$scope.showSessionTimeoutWarningModal();
$scope.stop();
}
}, 1000);
}
intializeSessionCounter();
...
$scope.stop = function () {
if( $scope.interval !== undefined){
$interval.cancel($scope.interval);
$scope.interval = undefined;
}
}
我很难取消我的 $interval 服务。我不完全确定我错过了什么。
我已经初始化了一个正在倒数的计数器 属性。 $scope.sessionCounter
$scope.sessionCounter = 5;
var intializeSessionCounter = function () {
$scope.sessionTime();
$interval(function () {
$scope.sessionCounter--;
if ($scope.sessionCounter > 1) {
console.log('timedown', $scope.sessionCounter);
}
else {
$scope.showSessionTimeoutWarningModal();
$scope.stop();
}
}, 1000);
}
intializeSessionCounter();
上面的一切都在通过 if 语句时工作正常。当 $scope.sessionCounter 转到 1 时,我点击了 else 语句。弹出我要打开的模式。 Next $scope.stop 被命中并且 $interval.cancel(null) 被读取。但是,没有任何取消,我的模式继续重新打开,因为 $interval 继续 运行 为负数。
$scope.stop = function () {
$interval.cancel(null);
}
您必须将 $interval 提供程序绑定到某个变量。
试试这个:
$scope.sessionCounter = 5;
var intializeSessionCounter = function () {
$scope.sessionTime();
$scope.interval = $interval(function () {
$scope.sessionCounter--;
if ($scope.sessionCounter > 1) {
console.log('timedown', $scope.sessionCounter);
}
else {
$scope.showSessionTimeoutWarningModal();
$scope.stop();
}
}, 1000);
}
intializeSessionCounter();
...
$scope.stop = function () {
if( $scope.interval !== undefined){
$interval.cancel($scope.interval);
$scope.interval = undefined;
}
}