Prabhagaran Palanisamy Prabhagaran Palanisamy - 3 days ago 4
Javascript Question

How to set interval time?

I have use following function for timer

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 am using
$rootScope.Minutes
and
$rootScope.Seconds
in view to display time. And time reduce by seconds . but if i close timer and open again it will reduce by 2 seconds. and again i close and open then it will reduce by 3 seconds. like wise iterations goes. I do not know where i did mistake. Please help me.

Answer

Every time you call startTimer, it will fire off another setInterval, which will run independently. Because you are using the same variables, each setInterval will operate on your $rootScope.timer variable independently.

The solution is to save a handle to the setInterval at the start, and clearInterval before setting a new interval.

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