Timers
Not everything on a website should happen instantly. Sometimes actions need to run after a delay or repeat automatically.
JavaScript timers make this possible by scheduling code to run later or repeatedly.
Why Timers Matter
Timers are used in many real-world situations:
- Showing notifications after a delay
- Auto-refreshing content
- Creating countdowns
- Running animations
They help control when code runs.
setTimeout()
setTimeout() runs a function once
after a specified delay (in milliseconds).
setTimeout(function () {
console.log("This runs after 2 seconds");
}, 2000);
The code inside runs only one time.
Real-World Use Case
Displaying a success message after an action:
setTimeout(function () {
alert("Profile updated successfully");
}, 1000);
This improves user experience by adding a natural delay.
setInterval()
setInterval() runs a function repeatedly
at a fixed interval.
setInterval(function () {
console.log("This runs every second");
}, 1000);
This continues until it is stopped.
Stopping a Timer
Timers can be stopped using their ID.
let timerId = setInterval(function () {
console.log("Running...");
}, 1000);
clearInterval(timerId);
This is important to avoid unnecessary background tasks.
Common Beginner Mistakes
- Forgetting timers keep running
- Using very short intervals unnecessarily
- Not clearing intervals when no longer needed
Always clean up timers to prevent performance issues.
Thumb Rules
- Use
setTimeout()for one-time delays - Use
setInterval()for repeated actions - Always store timer IDs
- Clear timers when done
What Comes Next?
Now that you understand timers, the next step is applying everything you’ve learned so far.
In the next lesson, we will build a DOM-based mini project.