freecoding.school100% FREE · NO SIGNUP
The DOM ForestISSUE #20 of 21

timing · setTimeout · setInterval · clearTimeout

NodetteVSThe Event Bubbler
Nodette sayssetTimeout runs code once after a delay; setInterval repeats — clear both by their id.

setTimeout(fn, ms) schedules one run; setInterval(fn, ms) repeats. Both return an id you pass to clearTimeout/clearInterval to cancel. Delays are a minimum, not exact — the callback waits for the call stack to clear. Always clear intervals you no longer need (e.g. on teardown) to avoid leaks.

Power-ups you unlock

The Event Bubbler attacks — common mistakes

Boss battleStart a countdown with setInterval and clear it when it reaches zero.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>let n=5;const o=document.getElementById('o');const id=setInterval(()=>{o.textContent=n;if(n--<=0){clearInterval(id);o.textContent='liftoff';}},300);</script></body></html>
▶ Open the interactive comic issue
‹ Custom Events · New CustomEvent · DispatchEventRequestAnimationFrame · The Render Loop ›