setTimeout and setInterval
setTimeout: run once, later
JavaScript
console.log("Ordering coffee...");
setTimeout(() => {
console.log("Coffee is ready!");
}, 1000);
console.log("Meanwhile, reading the news.");setTimeout(callback, ms) runs the callback once after at least ms milliseconds. Notice the order: JavaScript doesn't wait, it carries on and comes back when the timer fires.
setInterval: run repeatedly
JavaScript
let count = 3;
const id = setInterval(() => {
console.log(count);
count--;
if (count === 0) {
clearInterval(id); // stop the interval
console.log("Liftoff!");
}
}, 400);setInterval keeps going until you call clearInterval with the id it returned.
Cancelling a timeout
JavaScript
const reminder = setTimeout(() => console.log("You won't see this"), 1000);
clearTimeout(reminder);
console.log("Reminder cancelled");The event loop
JavaScript runs one thing at a time. Timer callbacks wait in a queue until the code currently running has finished, which is why even a 0 ms timeout runs after the code that follows it:
JavaScript
setTimeout(() => console.log("3: the timeout"), 0);
console.log("1: synchronous");
Promise.resolve().then(() => console.log("2: the promise"));Promise callbacks (microtasks) run before timer callbacks, which is why "2" comes before "3".
Debouncing: wait for a pause
A common use of timers is to wait until someone stops typing before doing expensive work, such as searching:
HTML
<input id="q" placeholder="Type to search...">
<p id="out" style="font-family: system-ui"></p>
<script>
let timer;
document.querySelector("#q").addEventListener("input", (e) => {
clearTimeout(timer); // restart the countdown on every key
timer = setTimeout(() => {
document.querySelector("#out").textContent = `Searching for "${e.target.value}"...`;
}, 400);
});
</script>The search runs only after 400 ms without a key press, instead of on every keystroke.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.