user3142695
user3142695

Reputation: 17342

Reset 'setIntervall' counter / remove existing instances

A timer will count down from 10 minutes on loading the page. If I do a mousedown after some time, the countdown should start again. But then the timer will jump between both values. It seems, that both are counting. How can I remove exiting intervals?

Template.content.onRendered(function() {
    var display = document.querySelector('#timer');

    startTimer( 600, display);
});

Template.content.events({
    'mousedown': function() {
        var display = document.querySelector('#timer');
        startTimer( 600, display);
        // this will start a new counter
        // but I want the old one to be replaced
    }
});

startTimer = function(duration, display) {
    var start = Date.now(),
        diff,
        minutes,
        seconds;
    function timer() {
        diff = duration - (((Date.now() - start) / 1000) | 0);
        minutes = (diff / 60) | 0;
        seconds = (diff % 60) | 0;

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds; 
    }
    timer();
    setInterval(timer, 1000);
};

Upvotes: 1

Views: 29

Answers (1)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28465

Add a new variable in your js

var timer = 0;

Update your code in startTimer function from

setInterval(timer, 1000);

to

timer = setInterval(timer, 1000);

And then in your mousedown event handler function, add following line

clearInterval(timer);

Upvotes: 1

Related Questions