2015-07-20 115 views
0

我有3個順序div顯示在一個頁面上,頁面加載顯示div 1,通過進入第二個啓動一個計時器,當這個計時器耗盡時它回到第一個div。導航到下一個div應該再次啓動定時器。定時器功能在第一頁上工作正常,但在第二頁上調用它時,它已經從前一個div運行,因此將時間縮短兩倍,最後一次減少3次。停止運行功能

我怎樣才能讓它停止當前運行的功能,然後重新啓動它?

感謝,

$scope.timeLeft = 0; 

    var timeoutRunner = function (timerLength) { 
    $scope.timeLeft = timerLength; 

    var run = function() { 

     if ($scope.timeLeft >= 1) { 
     console.log($scope.timeLeft); 
     $scope.timeLeft-- 
     $timeout(run, 1000); 
     } else if ($scope.timeLeft == 0){ 
     $scope.endTransaction(); 
     } 
    } 
    run(); 
    } 

timeoutRunner(5); 

回答

0

每次我把它叫做創建了一個功能它的新實例,我無法停止它的需求,所以我找到了一種方式來說我想要哪個實例運行:

$scope.timeLeft = 0; 
    var instanceRunning = 0; 

    var timeoutRunner = function (timerLength, instance) { 
    $scope.timeLeft = timerLength; 
    instanceRunning = instance; 

    var run = function() { 
     if (instanceRunning == instance){ 
     if ($scope.timeLeft < 7 && $scope.timeLeft > 0){ 
      $('#timer-container').show(); 
     } else { 
      $('#timer-container').hide(); 
     } 
     if ($scope.timeLeft >= 1) { 
      console.log($scope.timeLeft); 
      $scope.timeLeft-- 
      $timeout(run, 1000); 
     } else if ($scope.timeLeft == 0){ 
      $scope.endTransaction(); 
     } 
     } 
    } 
    run(); 
    } 


timeoutRunner(20, 1); 
timeoutRunner(20, 2); 
timeoutRunner(20, 3); 
0

您需要添加調用$timeout.cancel(timeoutRunner);一些邏輯。

0

不知道要準確地取消超時(?查看變化,當你結束交易),但這裏是你會怎麼做:

$scope.timeLeft = 0; 

var timeoutPromise = false; 

var timeoutRunner = function (timerLength) { 
    $scope.timeLeft = timerLength; 
    var run = function() { 
     if ($scope.timeLeft >= 1) { 
      console.log($scope.timeLeft); 
      $scope.timeLeft-- 
      timeoutPromise = $timeout(run, 1000); 
     } else if ($scope.timeLeft == 0){ 
      $scope.endTransaction(); 
      $timeout.cancel(timeoutPromise); 
     } 
    } 
    run(); 
} 

timeoutRunner(5);