我使用以下代码作为暂停定时器:
在angularjs中使用$timeout
时如何实现暂停和恢复功能
$scope.pause = function(){
window.clearTimeout(t);
}
timedcounter = function () {
time = time + 1;
localStorage.autotimertime = time;
t = $timeout(timedcounter, 1000);
display(time);
}
在这个代码片段中,我显示了时间,并使用了一个按钮来停止/重新启动超时。
您应该在onTimeout
函数中添加您的逻辑
var app = angular.module('myapp', []);
app.controller('myCtrl', function($scope, $timeout) {
$scope.time = 0;
$scope.stopped = false;
$scope.onTimeout = function() {
$scope.time = $scope.time + 1;
//Your logic here
//localStorage.autotimertime = time;
//display(time);
mytimeout = $timeout($scope.onTimeout, 1000);
}
var mytimeout = $timeout($scope.onTimeout, 1000);
$scope.stopTimeout = function() {
$scope.stopped = true;
$timeout.cancel(mytimeout);
}
$scope.restatTimeout = function() {
$scope.stopped = false;
mytimeout = $timeout($scope.onTimeout, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myCtrl">
<p ng-bind="time"></p>
<button ng-click="stopTimeout()" ng-show="!stopped">STOP ME !</button>
<button ng-click="restatTimeout()" ng-show="stopped">RESUME ME!</button>
</div>
要取消一个超时请求,调用$timeout.cancel(promise).