2015-07-20 114 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);