gpt4 book ai didi

javascript - 为什么我的 AngularJS 取消间隔不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 04:50:04 25 4
gpt4 key购买 nike

我想在按下停止计时器时停止倒计时。我不确定为什么这不起作用。我有一个简单的 jsfiddle 设置 here .

代码
查看

<div ng-app="timerApp" ng-controller="timerController">
<h4>Time Remaining: {{countdown}}</h4>
<button ng-click="startTimer()">Start Timer</button>
<button ng-click="stopTimer()">Stop Timer</button>
</div>

Controller

angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval', function ($scope, $interval) {
var timer;
var time = 10;
$scope.countdown = time;

$scope.stopTimer = function() {
$interval.cancel(timer);
};

$scope.startTimer = function() {
timer = $interval(function() {
$scope.countdown--;
}, 1000, time).then(function() {
$scope.countdown = time;
});
};

}]);

最佳答案

问题是调用then返回一个新的 promise ,而不是 $interval 返回的 promise 这是 $interval.cancel() 所要求的方法

angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval',
function($scope, $interval) {
var timer;
var time = 10;
$scope.countdown = time;

$scope.stopTimer = function() {
$interval.cancel(timer);
};

$scope.startTimer = function() {
timer = $interval(function() {
$scope.countdown--;
}, 1000, time);
timer.then(function() {
$scope.countdown = time;
});
};

}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="timerApp" ng-controller="timerController">
<h4>Time Remaining: {{countdown}}</h4>
<button ng-click="startTimer()">Start Timer</button>
<button ng-click="stopTimer()">Stop Timer</button>
</div>

关于javascript - 为什么我的 AngularJS 取消间隔不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33428156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com