Module 40 : Timers: setTimeout and setInterval.
📖 1. ntroduction to JavaScript Timers
Timers allow you to execute code after a delay (setTimeout) or repeatedly at intervals (setInterval). These are asynchronous operations handled by the browser’s Web API.
2. setTimeout() – One-time Delayed Execution
✅ Syntax:
let timeoutID = setTimeout(callback, delay, arg1, arg2, ...);
Parameters:
callback: Function to execute after delay.
delay: Time in milliseconds (1000 ms = 1 second).
arg1...: (Optional) Arguments passed to the callback.
Example 1: Simple Delayed Message
setTimeout(() => { console.log("Hello after 3 seconds!"); }, 3000);
Example 2: Using Named Function
function greet(name) { console.log(`Hello, ${name}!`); } setTimeout(greet, 2000, "Alice");
Cancelling a Timeout:
let id = setTimeout(() => console.log("This will not run"), 5000); clearTimeout(id);
3.setInterval() – Repeated Execution at Intervals
✅ Syntax:
let intervalID = setInterval(callback, interval, arg1, arg2, ...);
Example 3: Counting Every Second
let count = 1; let id = setInterval(() => { console.log(`Count: ${count++}`); }, 1000);
Cancelling an Interval:
clearInterval(id);
4. Exercise
Exercise 1: Countdown Timer (Practical Use Case)
Goal: Create a 5-second countdown using setInterval.
let countdown = 5; let timer = setInterval(() => { console.log(`Countdown: ${countdown}`); countdown--; if (countdown < 0) { clearInterval(timer); console.log("Time's up!"); } }, 1000);
Activity
Ask students to change it to 10 seconds.
Make it show a browser alert when finished.
5. Applications
Use Case
Timer Used
Explanation
Slideshow or carousel
setInterval
Automatically change slides after fixed time
Reminder notification
setTimeout
Show alert after a delay
Auto-logout
setTimeout
Log user out after inactivity
Stopwatch
setInterval
Update time display every second
Retry API call
setTimeout
Wait before retrying on failure
6. Common Mistakes
Mistake
What Happens
Forgetting clearTimeout()
Unnecessary delayed function runs
Forgetting clearInterval()
Infinite loop or memory issues
Not accounting for async delays
Function may not run at exact time due to JS event loop
Using large intervals in loops
Browser may throttle or ignore long intervals
📚 7. JS Event Loop and Timers
JavaScript is single-threaded, so timers are not guaranteed to run exactly on time.
Timers are handled via browser APIs (not the JS engine itself).
After the timer expires, the callback is queued in the event loop.
If the main thread is busy, the callback waits.
Try this to demonstrate:
setTimeout(() => console.log("Timeout"), 0); console.log("This logs first");
Output:
This logs first
Timeout
Even though delay is 0, it still waits until the current code completes.
🧠 8. Advanced Example: Traffic Light Simulator
let colors = ["Red", "Green", "Yellow"]; let index = 0; function changeLight() { console.log(`Light: ${colors[index]}`); index = (index + 1) % colors.length; } setInterval(changeLight, 2000);
9. Assignments
Create a Pomodoro Timer:
25 min work, 5 min break cycle using setTimeout.
Typing Practice Game Timer:
Countdown timer using setInterval.
Ends when timer reaches zero.
Animated Digital Clock:
Update time every second on screen.
📘 10. Notes
Start with a timer analogy (e.g., oven timer, alarm clock).
Introduce setTimeout with a greeting delay.
Move to setInterval with a counter example.
Show uses (e.g., reminder app, alert).
Code the countdown timer live.
Discuss clearTimeout and clearInterval.
Finish with exercises and Q&A.
Tips for Teachers:
Use browser console for live demos.
Highlight asynchronous nature with examples.
Encourage to break things and debug.
11. Research Insights
Browser Compatibility: Fully supported across all modern browsers.
Timers Throttling: In inactive tabs, browsers (like Chrome) throttle background setInterval to improve performance.
Node.js Timers: In Node, timers are available globally (setTimeout, setInterval) but managed differently than in the browser.
✅ Summary
Function
Description
Cancel With
setTimeout
Executes once after delay
clearTimeout()
setInterval
Executes repeatedly at fixed intervals
clearInterval()
Timers are powerful tools for handling delayed or periodic tasks. When used wisely, they help implement animations, reminders, games, and performance optimization features.
Optional
Countdown timer template code (HTML + JS)
Quiz on timers
Slide deck on timers and the event loop
No comments:
Post a Comment