back to series

Implement a resumable interval function

resumeInterval is a utility function using which we can create intervals that can be paused, restarted and stopped.

It takes the same signature as window.setInterval() and returns an object with the following methods:

  1. start: executes the callback immediately and every interval seconds.
  2. paused: pauses the running interval. Calling start again should restart the interval again.
  3. stop: permanently stops the interval. Once stopped, intervals can be started or paused again.

1. Basic implementation


./src/createResumableInterval.js
function createResumableInterval(callback, delay, ...args) {
let timerId = null;
let hasStopped = false;
function pause() {
// if stopped we return
if (hasStopped) {
return;
}
// we can stop only when timer id running, i.e timerId exists
if (timerId) {
clearInterval(timerId);
timerId = null;
}
}
function start() {
// if hasStopped, we return
if (hasStopped) {
return;
}
// we can start only when there is no timerId present
if (!timerId) {
callback();
timerId = setInterval(callback, delay, ...args);
}
}
function stop() {
// we can stop only created timers
if (!hasStopped && timerId) {
hasStopped = true;
clearInterval(timerId);
}
}
return {
start,
stop,
pause
};
}
let count = 0;
const interval = createResumableInterval(() => {
count++;
console.log(count);
}, 1000);
interval.start();
setTimeout(() => {
interval.pause();
}, 3500);
setTimeout(() => {
interval.start();
}, 4500);
setTimeout(() => {
interval.stop();
}, 6000);

Further Reading

I strongly encourage you to explore and tackle additional questions in my Closure Questions for Frontend Interviews blog series.

By doing so, you can enhance your understanding and proficiency with closures, preparing you to excel in your upcoming frontend interviews.

Wishing you best. Happy Interviewing 🫡.