gpt4 book ai didi

javascript - 在 Angular.js 中显示多个计时器功能

转载 作者:行者123 更新时间:2023-12-03 03:20:41 24 4
gpt4 key购买 nike

我试图在网页上显示两个具有不同开始时间的计时器。

第一个计时器仅显示 5 秒,10 秒后我需要显示计时器 2。我对 Angular 非常陌生,并编写了以下代码。

它似乎工作正常,除了第三次调用 settimeout 时它无法正常工作并且开始变得非常快。

Controller

 // initialise variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';

$scope.ti = 0;
$scope.startTimer1 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer1 = min + ":" + sec;
mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}

//start timer 1
$scope.startTimer1();

$scope.$watch('timer1',function(){

if($scope.timer1 !=undefined){
if($scope.timer1 =='00:05'){
$timeout.cancel(mytimeout1);
setInterval(function(){

$scope.startTimer2()
$scope.ti = 0;

},1000)
}
}

})

//start timer 2 after 2 mins and 20 seconds
$scope.startTimer2 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer2 = min + ":" + sec;
mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}


$scope.$watch('timer2',function(){

if($scope.timer2 !=undefined){
if($scope.timer2 =='00:05'){

$timeout.cancel(mytimeout2);

setInterval(function(){

$scope.startTimer1();
$scope.ti = 0;

},1000)


}
}

})

在我看来,我只是有

<p>{{timer1}}</p>

<p>{{timer2}}</p>

最佳答案

您基本上启动了多个 startTimer 函数,因此它正在累加。如果我很好地理解你的问题,你甚至不需要所有这些观察者和超时。您可以这样使用 $interval :

$scope.Timer = $interval(function () {

++$scope.tickCount

if ($scope.tickCount <= 5) {
$scope.timer1++
} else {
$scope.timer2++
if ($scope.tickCount >= 10)
$scope.tickCount = 0;
}
}, 1000);

工作中fiddle

关于javascript - 在 Angular.js 中显示多个计时器功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586005/

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