AngularJS计时器不会停止

时间:2015-01-07 15:23:31

标签: javascript angularjs

我正在运行以下代码,我正在尝试当它达到10秒时,基本停止计时器

 var mytimeout;
    $scope.startTimer = function() {
        $scope.counter = 0;
        $scope.onTimeout = function() {
            $scope.counter++;
            $log.info($scope.counter);
            if ($scope.counter == 10) {
                $scope.stop();
                $state.go($state.current.name, {}, {
                    reload: true
                })
            }
            mytimeout = $timeout($scope.onTimeout, 1000);

        }
        mytimeout = $timeout($scope.onTimeout, 1000);

    }

     $scope.stop = function(){
        $log.info("Stop");
        $timeout.cancel(mytimeout);
    }

日志如下:

angular.js:10126 1
angular.js:10126 2
angular.js:10126 3
angular.js:10126 4
angular.js:10126 5
angular.js:10126 6
angular.js:10126 7
angular.js:10126 8
angular.js:10126 9
angular.js:10126 10
angular.js:10126 Stop
angular.js:10126 11
angular.js:10126 12
angular.js:10126 13

1 个答案:

答案 0 :(得分:4)

您的计数器确实停止了,但是您在if语句之后重新分配mytimeout,以便计时器再次启动。我猜测$ state.go()仍在运行,但计数器在控制台中继续运行。

相反,如果小于10则调用定时器,否则调用解析函数。

$scope.startTimer = function() {
    $scope.counter = 0;
    $scope.onTimeout = function() {
        $log.info($scope.counter);

        if($scope.counter < 10){
            mytimeout = $timeout($scope.onTimeout, 1000)
        }else{
            $scope.stop();
            $state.go($state.current.name, {}, {
                reload: true
            })
        }

        $scope.counter++;
    }

    mytimeout = $timeout($scope.onTimeout, 1000);
}