如何设置间隔时间?

时间:2016-12-01 05:45:28

标签: javascript angularjs timer setinterval

我对计时器使用了以下功能

 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秒。就像明智的迭代一样。我不知道我错在哪里。请帮帮我。

1 个答案:

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