Search code examples
javascripttimersetinterval

How do I stop a setInterval timer in javaScript with an eventListener?


I'm trying to make a pomodoro timer just like the one on this page TomatoTimer

The problem is that I don't know if I'm taking the best approach.

I created this function:

function setTimer(minutes = "25") {
  let duration = minutes * 60 * 1000;
  let seconds = "00";
  let countdown = document.getElementById("timer");

  seconds = parseInt(seconds);
  minutes = parseInt(minutes);

  setInterval(() => {
    if (seconds === 0 && minutes > 0) {
      seconds = 60;
      minutes = minutes - 1;
      countdown.innerText = `${minutes}:${seconds}`;
    }
    if (seconds != 0) {
      seconds = seconds - 1;
    }

    if (seconds.toString().length === 1 && minutes.toString().length === 1) {
      countdown.innerText = `0${minutes}:0${seconds}`;
    } else if (minutes.toString().length === 1) {
      countdown.innerText = `0${minutes}:${seconds}`;
    } else if (seconds.toString().length === 1) {
      countdown.innerText = `${minutes}:0${seconds}`;
    } else {
      countdown.innerText = `${minutes}:${seconds}`;
    }

    duration = duration - 10000;
  }, 1000);
}

The minutes and seconds are strings because I want the timer to have this format (01:05) and if I work with numbers the "00" is "printed" as "0". From the third "if" statement to the end I'm formatting the output so that part is not that important, you could ignore it if you want.

After declaring that function I added an event listener to a button in order to call it, so far so good.

The problem is that I don't have the slightest idea of how to stop the timer.

The only thing I want is to stop that function from executing, I don't want the app to remember what time it was and restart from there, I'll do that later.

I tried multiple things, one of them was to use the clearInterval method, but I saw that you must store the interval inside a variable and when I do that the I'm not able to call the function with my eventListener.

I have a couple of questions:

  • It would be better to create the interval outside the function?
  • Is "setInterval" the way to go?
  • Is it possible to stop the timer having the function I created?

If you want to have a better idea of what I'm making and what I've done so far, you can check all my code in codepen.


Solution

  • A good idea is to keep track of the remaining time of the Timer (until reaching 00:00), so when you pause the Timer you simply call clearInterval, and when you want to resume it, simply call again setInterval, but now using the remaining time as an imput.

    And to solve your problem of keeping the reference to the interval, you may want to return it from your setTimer function. Just to keep your code tidy, I suggest you create a Timer class that manages all the "state" of your timer and also provides methods to interact with it (like pause(), stop(), resume(), reset()).