gpt4 book ai didi

AngularJS - 如何制作从 00 :00:00 format 开始的秒表

转载 作者:行者123 更新时间:2023-12-02 06:09:32 24 4
gpt4 key购买 nike

我想创建一个秒表。我用谷歌搜索并得到了一些关于如何制作计时器的提示。这是我在 Controller 中所做的事情:

$scope.value = 0;
$scope.startTimer = function() {

$scope.value = 0;

var change = function() {
$scope.value += 1000;
$timeout(change,1000);
};
$timeout(change, 1000);
}

在我的 html 中以这种格式显示值:

<label>{{value | date: 'hh:mm:ss'}}</label>

问题是时钟总是从 04:00:00 开始,当我调用 startTimer() 函数时,它会启动计时器,但我希望计时器如下:

00:00:00

00:00:01

00:00:02

...

谁能告诉我如何在 00:00:00 启动计时器?

最佳答案

已编辑:使用间隔计时器更新了代码,因此现在代码包含带有 $timeout$interval 的计时器。
在这里,制作您自己的过滤器:

var app = angular.module("myApp",[]);
app.controller("myController",function($scope, $timeout, $interval){

//timer with timeout
$scope.timerWithTimeout = 0;
$scope.startTimerWithTimeout = function() {
$scope.timerWithTimeout = 0;
if($scope.myTimeout){
$timeout.cancel($scope.myTimeout);
}
$scope.onTimeout = function(){
$scope.timerWithTimeout++;
$scope.myTimeout = $timeout($scope.onTimeout,1000);
}
$scope.myTimeout = $timeout($scope.onTimeout,1000);
};

$scope.resetTimerWithTimeout = function(){
$scope.timerWithTimeout = 0;
$timeout.cancel($scope.myTimeout);
}

//timer with interval
$scope.timerWithInterval = 0;
$scope.startTimerWithInterval = function() {
$scope.timerWithInterval = 0;
if($scope.myInterval){
$interval.cancel($scope.myInterval);
}
$scope.onInterval = function(){
$scope.timerWithInterval++;
}
$scope.myInterval = $interval($scope.onInterval,1000);
};

$scope.resetTimerWithInterval = function(){
$scope.timerWithInterval = 0;
$interval.cancel($scope.myInterval);
}
})
app.filter('hhmmss', function () {
return function (time) {
var sec_num = parseInt(time, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);

if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<label>Timer with timeout: {{timerWithTimeout | hhmmss}}</label>
<button ng-click="startTimerWithTimeout()">Start Timer</button>
<button ng-click="resetTimerWithTimeout()">reset tiemr</button>
<br><br>
<label>Timer with interval: {{timerWithInterval | hhmmss}}</label>
<button ng-click="startTimerWithInterval()">Start Timer</button>
<button ng-click="resetTimerWithInterval()">reset tiemr</button>
</div>

补充:对于计时器,最好使用$interval而不是$timeout。并始终将 $interval 引用到某个变量:$scope.timer = $interval(change, 1000); ,这样您就可以在每次重置时销毁它:$interval.cancel($scope.计时器); .

关于AngularJS - 如何制作从 00 :00:00 format 开始的秒表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32285679/

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