2017-10-05 16 views
0

我试图在具有不同开始时间的网页上显示两个计时器。在Angular.js中显示多个计时器功能

第一个定时器只显示5秒,然后10秒后我需要显示timer2。 我对Angular非常陌生,并将以下代码放在一起。

它似乎工作正常,除非settimeout被称为第三次它不能正常工作,并且它开始非常快。

控制器

// 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> 
+0

你不应该使用的setInterval但$间隔。 – yeouuu

回答

1

你基本上启动多个startTimer所的功能,所以它加起来。如果我理解你的问题,你甚至不需要拥有所有的观察者和超时。 你只可以使用$间隔是这样的:

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

    ++$scope.tickCount 

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

工作fiddle

+0

谢谢,但我需要在几分钟内显示两个“加计数”定时器:秒格式。当第一个到达02:00时需要停止/暂停,第二个定时器应该从00:01开始。一旦第二个定时器到达02:00它暂停,然后第一个定时器再次回收。因此我使用手表。 – snowflakes74

+0

检查新的小提琴,它应该是你要找的东西 - 请注意,我没有格式化定时器,但是你可以使用整数的代码示例将其格式化为mm:ss –

+1

谢谢你向我展示如何有效解决我的问题。 – snowflakes74