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 requestAnimationFrame instead.
  • 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

  1. Write a setTimeout that logs “Start” after 3 seconds.
  2. How would you stop a setInterval that runs every 500 ms?
  3. Explain a scenario where setTimeout is better than setInterval.
  4. What happens if the callback function of a setInterval takes 2 seconds to execute but the interval is set to 1 second?

Revision

Log in to practice.

0 views 0 suggestions