Can't reset timer with clearInterval();

You must Login before you can answer or comment on any questions.

I am trying to start a timer with a click event and be able to reset the timer back from zero if the same button is pressed but every time I press the button that initiates the setInterval it seems to be creating a new interval and not reseting the one that was already creating. Can someone help please? This is my code:

startbtn.addEventListener('click', function(e) {
    clearInterval(timer);
    var count = 0;
    var timer = setInterval(function()
    {
 
        count++;
        testlbl.text = count;
        if (count === 10){
            clearInterval(timer);
            testlbl.text = 'stopped';
        }
 
 
      stopbtn.addEventListener('click', function(e) {
        clearInterval(timer);
        testlbl.text = 'stopped by button';
      });
 
 
    },1000);    
});

1 Answer

Accepted Answer

Try this:

var timer;
startbtn.addEventListener('click', function(e) {
    if(timer) {
        clearInterval(timer);
        timer = null;
    }
 
    var count = 0;
    timer = setInterval(function() {
        count++;
        testlbl.text = count;
        if(count === 10) {
            clearInterval(timer);
            timer = null;
            testlbl.text = 'stopped';
        }
    }, 1000);
});
 
stopbtn.addEventListener('click', function(e) {
    if(timer) {
        clearInterval(timer);
        timer = null;
    }
    testlbl.text = 'stopped by button';
});

— answered 1 year ago by Minh Nguyen
answer permalink
2 Comments
  • This worked perfectly. I have another question now. How can I pause the timer so it can resume where it left off with a third button?

    — commented 1 year ago by Raul Ochoa

  • There's no resumeInterval method.. But you can simulate it by storing current count, then when user click Resume, count will continue to be count up.

    var timer;
    var count = 0;
    var isStartMode = true;
     
    startbtn.addEventListener('click', function(e) {
        if(timer) {
            clearInterval(timer);
            timer = null;
        }
     
        if (isStartMode) {
            count = 0;  
        }
     
        timer = setInterval(function() {
            count++;
            testlbl.text = count;
            if(count === 10) {
                clearInterval(timer);
                timer = null;
                testlbl.text = 'stopped';
            }
        }, 1000);
     
        isStartMode = true;
    });
     
    stopbtn.addEventListener('click', function(e) {
        if(timer) {
            clearInterval(timer);
            timer = null;
        }
        testlbl.text = 'stopped by button';
    });
     
    resumebtn.addEventListener('click', function(e) {
        isStartMode = false;
            startbtn.fireEvent('click');
    });

    — commented 1 year ago by Minh Nguyen

Your Answer

Think you can help? Login to answer this question!