2016-12-01 3 views
0

Ich habe Gebrauch folgende Funktion für TimerWie stelle ich die Intervallzeit ein?

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); 

I $rootScope.Minutes und $rootScope.Seconds in Sicht bin mit der Zeit angezeigt werden soll. Und die Zeit wird um Sekunden reduziert. Aber wenn ich den Timer schließe und wieder öffne, wird er um 2 Sekunden reduziert. und wieder schließe ich und öffne es dann um 3 Sekunden. Wie weise Iterationen geht. Ich weiß nicht, wo ich Fehler gemacht habe. Bitte hilf mir.

+0

post voller Code in Geige. –

Antwort

0

Jedes Mal, wenn Sie startTimer anrufen, wird ein weiterer setInterval ausgelöst, der unabhängig ausgeführt wird. Da Sie die gleichen Variablen verwenden, wird jede setInterval unabhängig von Ihrer $rootScope.timer Variable arbeiten.

Die Lösung besteht darin, am Anfang ein Handle zu setInterval und clearInterval vor dem Festlegen eines neuen Intervalls zu speichern.

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

Danke ..Es funktioniert. –

Verwandte Themen