简体   繁体   English

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

[英]Showing multiple timer function in Angular.js

I am trying to display two timer on a webpage with different start times. 我正在尝试在具有不同开始时间的网页上显示两个计时器。

First timer only shows for 5 seconds and then after 10 seconds I need to show timer2. 第一个计时器只显示5秒钟,然后10秒钟后我需要显示timer2。 I am very new to Angular and have put together following code. 我是Angular的新手,并整理了以下代码。

It seems to be working fine except when the settimeout is called the third time it doesn't work correctly and it starts going very fast. 似乎工作正常,除非第三次调用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)


        }
    }

})

In my view I simply have 我认为我只是

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

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

You're basically starting multiple startTimer function so it's adding up. 您基本上是在启动多个startTimer函数,所以它正在累加。 If i understood your problem well you don't even need to have all those watchers and timeouts. 如果我很好地理解了您的问题,您甚至不需要所有这些监视程序和超时。 You just can use $interval this way : 您可以这样使用$ interval:

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

  ++$scope.tickCount

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

Working fiddle 工作提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM