setTimeout
Schedule one callback for later.
Timers schedule work for later or repeatedly, but they are scheduling tools, not precise real-time clocks.
const id = setInterval(updateClock, 1000); clearInterval(id);
Async JavaScript
setTimeout schedules a callback after a delay. setInterval schedules repeated callbacks at roughly the interval you request.
Both return an id. You can pass that id to clearTimeout or clearInterval to cancel scheduled work.
Timers can drift when the main thread is busy or the tab is backgrounded. Do not use them as perfect clocks.
Schedule one callback for later.
Cancel a pending timeout.
Run repeatedly.
Stop repeated work.
Examples
const intervalId = setInterval(updateStatus, 1000);
stopButton.addEventListener("click", () => {
clearInterval(intervalId);
});
setInterval(updateStatus, 1000); // This keeps running until the page unloads.
Code patterns
These examples are the async patterns you will reuse: timers, promises, composition, await, fetch and cancellation.
One delayed callback.
const id = setTimeout(() => {
showMessage();
}, 1000);
Stop before it fires.
clearTimeout(id);
Run on an interval.
const id = setInterval(update, 1000);
Useful when each step decides the next delay.
function tick() {
update();
setTimeout(tick, 1000);
}
Rules that matter
Async JavaScript is easier when every operation has clear pending, success, failure and cancellation behavior.
You need the id to cancel.
Repeating work should have a stop path.
Timers wait for the main thread.
Centralize repeated work where possible.
It avoids overlapping interval work.
Heavy callbacks still freeze the page.
Production thinking
Timers are common in UI feedback, polling, animation helpers and delayed actions.
Timed UI should not remove content before users have time to read or interact.
Production timer code needs cleanup when panels close, components unmount or polling stops.
Timer-delayed critical content can be missed or delayed for users and crawlers.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain when the code runs, how it fails and what happens if it becomes irrelevant, you understand the async model.