gpt4 book ai didi

javascript - 在 angularjs 中使用 $timeout 时如何暂停和恢复计时器

转载 作者:太空宇宙 更新时间:2023-11-04 16:28:17 25 4
gpt4 key购买 nike

我使用此代码作为暂停计时器:

在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>

关于javascript - 在 angularjs 中使用 $timeout 时如何暂停和恢复计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40036326/

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