Skip to content

CodeNot attempted

setInterval using setTimeout

Difficulty: easy

Implement mySetInterval(fn, ms) with only setTimeout. Return a function that stops it, and make sure fn can stop the interval from inside itself.

Follow-up: why do some people prefer recursive setTimeout over setInterval? (no overlapping runs when fn is slow)

Show reference solution
export function mySetInterval(fn: () => void, interval: number): () => void {
let active = true;
let timer: ReturnType<typeof setTimeout>;
function run() {
if (!active) return;
fn();
if (active) {
timer = setTimeout(run, interval); // fn may have stopped us
}
}
timer = setTimeout(run, interval);
return () => {
active = false;
clearTimeout(timer);
};
}
Loading editor…