Timers
This lesson explains Timers in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.
JavaScript Timers Overview
JavaScript timers allow code to execute after a specified delay or at
repeated intervals. Timers are powered by browser or Node.js runtime APIs
and are commonly used for animations, notifications, countdowns, auto-save,
polling, slideshows, debouncing, and periodic data refresh.
The two primary timer functions are setTimeout() and
setInterval(). Timers can be canceled using
clearTimeout() and clearInterval(). Understanding
timers is essential for asynchronous JavaScript, event loops, UI updates,
and performance optimization.
| Timer Function | Description | Common Usage |
| setTimeout() | Runs a function once after a delay. | Notifications and delayed actions. |
| clearTimeout() | Cancels a scheduled timeout. | Cancel delayed operations. |
| setInterval() | Runs a function repeatedly. | Polling and live updates. |
| clearInterval() | Stops a repeating timer. | Stop countdowns and refreshes. |
| requestAnimationFrame() | Runs before the next browser repaint. | Animations. |
| Timer ID | Identifier returned by timer functions. | Cancel scheduled timers. |
JavaScript Timer Example
const timeoutId = setTimeout(function() {
console.log("Runs once after 2 seconds");
}, 2000);
const intervalId = setInterval(function() {
console.log("Runs every second");
}, 1000);
setTimeout(function() {
clearInterval(intervalId);
console.log("Interval stopped");
}, 5000);
This example uses setTimeout() for a one-time task,
setInterval() for repeated execution, and
clearInterval() to stop the repeating timer after five seconds.
Top 10 JavaScript Timer Examples
The following examples demonstrate the most common timer patterns used in
modern JavaScript applications.
| # | Example | Syntax |
| 1 | Run Once | setTimeout(function() { console.log("Done"); }, 1000); |
| 2 | Cancel Timeout | clearTimeout(timeoutId); |
| 3 | Run Repeatedly | setInterval(function() { refresh(); }, 5000); |
| 4 | Stop Interval | clearInterval(intervalId); |
| 5 | Arrow Function Timer | setTimeout(() => console.log("Hello"), 1000); |
| 6 | Pass Arguments | setTimeout(showMessage, 1000, "Welcome"); |
| 7 | Recursive Timeout | function poll() { setTimeout(poll, 5000); } |
| 8 | Animation Frame | requestAnimationFrame(updateAnimation); |
| 9 | Debounce Timer | clearTimeout(timer); timer = setTimeout(search, 300); |
| 10 | Countdown Timer | const id = setInterval(updateCountdown, 1000); |
Popular Real-World JavaScript Timer Examples
These examples show how timers are commonly used in production applications
for user interactions, live updates, animations, and background tasks.
| Scenario | Timer Pattern |
| Hide Notification | setTimeout(hideNotification, 3000); |
| Auto Logout | setTimeout(logoutUser, 1800000); |
| Auto Refresh Dashboard | setInterval(loadDashboardData, 60000); |
| Countdown Clock | setInterval(updateClock, 1000); |
| Search Debouncing | clearTimeout(timer); timer = setTimeout(searchProducts, 300); |
| Typing Indicator | setTimeout(clearTypingStatus, 1500); |
| Image Slideshow | setInterval(showNextImage, 5000); |
| Retry API Request | setTimeout(fetchData, 2000); |
| Smooth Animation | requestAnimationFrame(animate); |
| Polling API | setInterval(checkOrderStatus, 10000); |
Best Practices
- Use
setTimeout() for one-time delayed tasks. - Use
setInterval() only for tasks that must repeat continuously. - Always clear unused timers with
clearTimeout() or clearInterval(). - Prefer recursive
setTimeout() over setInterval() for API polling to avoid overlapping requests. - Use
requestAnimationFrame() for smooth browser animations. - Store timer IDs so they can be canceled later.
- Keep timer callbacks lightweight to avoid blocking the UI.
- Use debouncing or throttling for high-frequency user events.
Common Mistakes
- Forgetting to cancel timers when they are no longer needed.
- Assuming
setTimeout() runs exactly on schedule. - Using
setInterval() for slow API requests that may overlap. - Creating multiple intervals accidentally.
- Passing the result of a function instead of the function itself.
- Using timers for animations instead of
requestAnimationFrame(). - Ignoring timer cleanup when components or pages are destroyed.
Key Takeaways
setTimeout() executes code once after a delay. setInterval() executes code repeatedly until canceled. clearTimeout() cancels delayed execution. clearInterval() stops repeating timers. requestAnimationFrame() is preferred for browser animations. - Always clean up timers to improve application performance.
- Timers are fundamental for asynchronous JavaScript and user interactions.
Pro Tip
For repeated API requests, prefer a recursive
setTimeout() instead of setInterval(). It waits
for one request to finish before scheduling the next, preventing overlapping
network calls and improving reliability.