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);
}
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.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!