JS DOM: setTimeout, setInterval
(parts AI generated) work in progress
what is setTimeout and setInterval
setTimeout is a browser function that lets you schedule code to run after a delay.
setInterval is for running at regular intervals.
They are essential for animations, auto-saving, countdowns, etc.
setTimeout
setTimeout(f, delayInMilliseconds, args)-
call a function after a delay.
- f → Function to run.
- delayInMilliseconds → delay, in milliseconds.
- args → Optional arguments passed to f.
- Returns a id, for
clearTimeout(id).
setTimeout(() => { console.log("hi after 2 seconds!"); }, 2000);
Passing arguments:
const ff = (name, age) => { console.log(`Hello ${name}.`); }; setTimeout(ff, 1000, "Alice"); // Hello Alice.
setInterval. Run Repeatedly Every Interval
setInterval(f, delayInMilliseconds, args)-
call a function at every time interval.
- f → Function to run.
- delayInMilliseconds → interval in milliseconds.
- args → Optional arguments passed to f.
- Returns a id, for
clearInterval(id).
let count = 0; const intervalId = setInterval(() => { count++; console.log(`Count: ${count}`); if (count >= 5) { clearInterval(intervalId); console.log("Stopped"); } }, 1000);
3. Clearing Timers
clearTimeout(timeoutId); clearInterval(intervalId);
Important: You can call clearTimeout on an interval ID and vice versa (they share the same ID pool), but it's best practice to use the matching clear function.
Example of canceling:
const id = setTimeout(() => console.log("This won't run"), 5000); // Cancel immediately clearTimeout(id);
4. Complete Practical Examples
Countdown Timer
/* countdown. print 10 9 8 ... to 0, one sec at a time. */ let timeLeft = 10; const f_print_time_left = (x) => { console.log(timeLeft); timeLeft--; if (timeLeft < 0) { clearInterval(countdown); console.log("Time's up!"); } }; const countdown = setInterval(f_print_time_left, 1000);
Simple Animation (moving a box)
<div id="box" style="position:absolute; width:50px; height:50px; background:red;"></div> <script> const box = document.getElementById('box'); let position = 0; const animate = setInterval(() => { position += 5; box.style.left = position + 'px'; if (position > 500) clearInterval(animate); }, 20); // ~50fps </script>
Debouncing User Input (common in search boxes)
let timeout; const input = document.getElementById('search'); input.addEventListener('input', () => { clearTimeout(timeout); // cancel previous timeout = setTimeout(() => { console.log("Searching for:", input.value); // perform expensive search }, 300); // wait until user stops typing });
5. Key Concepts and Gotchas
The callback loses its this context unless you use an arrow function or .bind().
const xobj = { name: "Joe", greet() { console.log("name is:", this.name); } }; // Wrong - this becomes window/global setTimeout(xobj.greet, 1000); // name is: // Correct ways: setTimeout(() => xobj.greet(), 1000); // name is: Joe // setTimeout(xobj.greet.bind(xobj), 1000);
Minimum delay and throttling
Browsers clamp delays below 4ms to 4ms for setTimeout/setInterval when called from the main thread after the first execution. Nested timers have even higher minimums (for security/performance).
Not precise timing Timers are not guaranteed to fire exactly on time. They are scheduled when the event loop is free. Heavy computation or long tasks delay them.
Modern alternatives
requestAnimationFrame()for smooth animations (syncs with screen refresh).AbortController+setTimeoutfor cancellable timers (more modern pattern).
6. Promise-based Version (Useful for async/await)
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // Usage async function run() { console.log("Start"); await delay(2000); console.log("After 2s"); }
tips
- Always store and clear timer IDs when possible.
- Use arrow functions for simple callbacks to preserve
this. - Prefer
requestAnimationFrameoversetIntervalfor UI animations.