2016-12-01 123 views
0

我有使用以下定时器如何设置间隔时间?

function startTimer(duration) { 
     $rootScope.timer = duration; 
     $rootScope.minute = 0; 
     $rootScope.second = 0; 
     $rootScope.Minutes = 0; 
     $rootScope.Seconds = 0; 
     setInterval(function() { 
      $rootScope.minute = parseInt($rootScope.timer/60, 10) 
      $rootScope.second = parseInt($rootScope.timer % 60, 10); 
      $rootScope.Minutes = $rootScope.minute < 10 ? "0" + 
      $rootScope.minute : $rootScope.minute; 
      $rootScope.Seconds = $rootScope.second < 10 ? "0" + 
      $rootScope.second : $rootScope.second; 
      if (--$rootScope.timer < 0) { 
       $rootScope.timer = duration; 
      } 
     }, 1000); 
    } 

startTimer(300); 

我使用$rootScope.Minutes$rootScope.Seconds在视图中显示时间的功能。时间以秒为单位减少。但如果我关闭计时器并再次打开它会减少2秒。再次关闭并打开,然后它会减少3秒。就像明智的迭代一样。我不知道我犯了什么错误。请帮帮我。

+0

在小提琴中发布完整的代码。 –

回答

0

每当您拨打startTimer时,它会触发另一个setInterval,它将独立运行。由于您使用的变量相同,因此每个setInterval将独立运行在您的$rootScope.timer变量上。

解决的办法是在开始时保存一个句柄到setInterval,在设置一个新的时间间隔之前保存一个句柄到clearInterval

function startTimer(duration) { 
     $rootScope.timer = duration; 
     $rootScope.minute = 0; 
     $rootScope.second = 0; 
     $rootScope.Minutes = 0; 
     $rootScope.Seconds = 0; 

     // modified bit 
     if($rootScope.internvalhandle) clearInterval($rootScope.internvalhandle); 

     $rootScope.internvalhandle = setInterval(function() { 
      $rootScope.minute = parseInt($rootScope.timer/60, 10) 
      $rootScope.second = parseInt($rootScope.timer % 60, 10); 
      $rootScope.Minutes = $rootScope.minute < 10 ? "0" + 
      $rootScope.minute : $rootScope.minute; 
      $rootScope.Seconds = $rootScope.second < 10 ? "0" + 
      $rootScope.second : $rootScope.second; 
      if (--$rootScope.timer < 0) { 
       $rootScope.timer = duration; 
      } 
     }, 1000); 
    } 

startTimer(300); 
+0

谢谢..它正在工作。 –