LearnFrenzy
Sign in Take a free test

Event Loop · Event Loop Coding Problems · Question 6

Build an interval with recursive setTimeout in JavaScript Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write every(ms, fn, times) using recursive setTimeout instead of setInterval: it runs fn the given number of times, never overlapping, and returns a stop function.

Solution
main.js
function every(ms, fn, times) {
  let count = 0, timer = null, stopped = false;
  function run() {
    if (stopped) return;
    fn(++count);
    if (count < times) timer = setTimeout(run, ms);   // schedule the next run only after this one finished
  }
  timer = setTimeout(run, ms);
  return () => { stopped = true; clearTimeout(timer); };
}

every(5, (n) => {
  console.log(`heartbeat ${n}`);
  if (n === 3) startPolling();                 // heartbeats are done: start a second job
}, 3);

function startPolling() {
  const stop = every(5, (n) => {
    console.log(`poll ${n}`);
    if (n === 4) { stop(); console.log("polling stopped"); }   // stop from outside the `times` limit
  }, 100);
}

Output Verified by running it on Node.js

heartbeat 1
heartbeat 2
heartbeat 3
poll 1
poll 2
poll 3
poll 4
polling stopped

Unlike setInterval, the next run is scheduled only after the current one completes, so slow callbacks never pile up. The heartbeat stops by itself after 3 runs; the poller would run 100 times, but stop() clears its pending timer after the fourth.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links