Use JavaScript timing events (setTimeout, setInterval)
21 Programming for the web: Timing Events
What are Timing Events?
Think of timing events like a timer on a kitchen oven – you set a time, and after that time, something happens. In JavaScript, setTimeout and setInterval let you schedule actions.
setTimeout
Syntax: setTimeout(callback, delay) where delay is in milliseconds.
Example: setTimeout(() => console.log('Hello!'), 2000); – prints “Hello!” after 2 seconds.
Analogy: “Set a timer for 2 minutes and then start boiling the pasta.”
Use cases:
- Delaying a message or animation.
- Waiting for a resource to load before executing code.
- Debouncing user input (e.g., search suggestions).
setInterval
Syntax: setInterval(callback, delay) – repeats every delay milliseconds.
Example: setInterval(() => console.log('Tick'), 1000); – logs “Tick” every second.
Analogy: “Set a metronome to tick every second.”
Use cases:
- Updating a clock or countdown timer.
- Polling a server for updates.
- Creating animations that loop.
Key Differences
| Feature | setTimeout | setInterval |
|---|---|---|
| Runs once or repeatedly | Once | Repeatedly |
| Use for delayed actions | ✓ | ✗ |
| Use for periodic actions | ✗ | ✓ |
| Can be cancelled | Yes – clearTimeout(id) |
Yes – clearInterval(id) |
Common Pitfalls
- Using setInterval for animations: If the callback takes longer than the interval, frames can pile up. Use
requestAnimationFrameinstead. - Forgetting to clear: A timer that never stops can keep the page busy. Always store the returned ID and clear when appropriate.
- Delay confusion: 1000 ms = 1 second. Remember the conversion when planning delays.
Exam Tips
🔍 Understand the difference between setTimeout and setInterval. You may be asked to explain why one is preferred over the other in a given scenario.
📝 Write clear code snippets. Show the syntax and explain the parameters.
💡 Use analogies. Relate timers to everyday objects (e.g., kitchen timers, metronomes).
⚠️ Don’t forget to mention clearTimeout/clearInterval. It demonstrates awareness of resource management.
Practice Questions
- Write a
setTimeoutthat logs “Start” after 3 seconds. - How would you stop a
setIntervalthat runs every 500 ms? - Explain a scenario where
setTimeoutis better thansetInterval. - What happens if the callback function of a
setIntervaltakes 2 seconds to execute but the interval is set to 1 second?
Revision
Log in to practice.