Saltar al contenido

CódigoSin intentar

setInterval usando setTimeout

Dificultad: fácil

Implementa mySetInterval(fn, ms) solo con setTimeout. Devuelve una función que lo detenga, y asegúrate de que fn pueda detener el intervalo desde dentro.

Para profundizar: ¿por qué algunos prefieren setTimeout recursivo a setInterval? (no hay ejecuciones solapadas cuando fn es lento)

Ver solución de referencia
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);
};
}
Cargando editor…