Lesson 7
Timers
Build a practical mental model for timers and use it in working JavaScript.
By the end, you will be able to…
- Explain timers in your own words
- Use timers in a small program
- Recognize and debug a common failure mode
Build the mental model
setTimeout schedules a callback to run once after a delay; setInterval repeats it. Both return an id you can pass to clearTimeout/clearInterval to cancel the scheduled work.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Forgetting to clear timers is a classic source of memory leaks and 'why is this still running after I navigated away' bugs.
Real-world example
A toast notification that auto-dismisses after 3 seconds, but clears its timer early if the user dismisses it manually first.
Common mistakes
- Never clearing a timer when the component or feature using it goes away
- Assuming setTimeout(fn, 0) runs synchronously (it still waits for the call stack to clear first)
- Using setInterval when a single setTimeout would do
Try it yourself
Challenge
Write a debounced-style scheduler stub: scheduleOnce(fn, ms) returns a cancel function.
Knowledge check
What does setTimeout(fn, 0) actually guarantee?
Summary
Schedule with setTimeout/setInterval, and always keep the id so you can cancel it when it's no longer needed.