JavaScript Timers and Intervals
# JavaScript Timers and Intervals
Sometimes you don't want your code to run immediately. You might want to wait 3 seconds before showing a popup ad, or you might want to refresh a user's notification feed every 10 seconds.
In this chapter, we will learn how to control time using the browser's built-in Timer functions.
1. Introduction
JavaScript provides two primary methods for executing code at specified time intervals:
-
1.
setTimeout(): Executes a function exactly once, after a specified delay.
-
2.
setInterval(): Executes a function repeatedly, waiting a specified delay between each execution.
Both of these functions belong to the global window object, meaning you can call them from anywhere in your code.
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Use
setTimeoutto delay code execution.
- Pass arguments to timer callbacks.
-
Cancel a delayed execution using
clearTimeout.
-
Use
setIntervalto create loops over time.
-
Stop recurring executions using
clearInterval.
- Build a working Stopwatch / Timer mini-project.
3. setTimeout Syntax
The setTimeout function takes two mandatory parameters:
- 1. A callback function (the code to run).
- 2. The delay in milliseconds (1000 ms = 1 second).
4. setInterval Syntax
The setInterval function uses the exact same syntax, but it will loop indefinitely until you manually stop it or close the tab.
---
5. Real-world Examples & Code Snippets
Example 1: Showing a Notification Toast
A common use case is displaying a "Saved Successfully!" toast notification, then making it disappear after 3 seconds.
Example 2: Passing Arguments to Timers
If you need to pass data to the callback function, you add them as additional arguments after the delay parameter.
Example 3: Canceling a Timeout (clearTimeout)
If the user clicks "Undo", you want to cancel the delete operation before the timeout finishes. setTimeout returns a unique ID number. You pass this ID to clearTimeout().
Example 4: A Digital Clock (setInterval)
We used this in Chapter 14. We want to update the DOM every 1000 milliseconds.
Example 5: Stopping an Interval (clearInterval)
Just like timeouts, intervals return an ID. You must save this ID if you ever want to stop the loop.
Example 6: The "Zero Delay" Trick
Sometimes you will see setTimeout(func, 0). Why wait 0 seconds? Because JavaScript is single-threaded. By putting a function in a timeout, you push it to the back of the "Event Queue", telling the browser to finish drawing the current HTML screen BEFORE running this heavy function.
Example 7: Using Timers for Animations
Before CSS animations were powerful, developers used setInterval to move elements 1 pixel at a time. While CSS is better now, JS timers are still used for complex canvas game animations.
---
6. Common Mistakes for Beginners
-
1.
Adding
()to the callback:setTimeout(myFunc(), 1000)executesmyFuncIMMEDIATELY and passes its return value into the timer. You must pass the function reference:setTimeout(myFunc, 1000)or use an arrow functionsetTimeout(() => myFunc(), 1000).
-
2.
Losing track of Interval IDs: If you write
setInterval(func, 1000)without assigning it to a variable (const id = ...), that loop will run forever, and you have no way to target it to stop it. If you trigger it on a button click, clicking the button 5 times will start 5 concurrent loops!
7. Best Practices
-
Always use Arrow Functions for timer callbacks. As discussed in Chapter 20, arrow functions inherit
thisfrom the surrounding scope, which preventsthisfrom breaking inside the timer.
- Always clear your intervals. If a user navigates to a new "page" in a Single Page App (like React), uncleared intervals will continue running in the background, causing memory leaks and terrible performance.
8. Mini Project: Interactive Stopwatch
Let's build a functional stopwatch with Start, Stop, and Reset buttons using setInterval.
HTML:
stopwatch.js:
9. Exercises
-
1.
Write a
setTimeoutthat console logs "Warning: 5 seconds left!" after a 5000ms delay.
-
2.
Write a
setIntervalthat prints "Tick" every 1000ms. Assign it to a variable namedticker.
-
3.
Write a single line of code to stop the
tickerinterval from running.
10. MCQs (Multiple Choice Questions)
Q1: Which function runs code repeatedly at a set interval?
A) setTimeout()
B) setRecurring()
C) setInterval()
D) clearTimeout()
*Answer: C*
Q2: What argument does clearInterval() require?
A) The string name of the function being looped.
B) The ID returned by setInterval().
C) The amount of time in milliseconds.
D) The document object.
*Answer: B*
Q3: Which time unit do JavaScript timers use? A) Seconds B) Microseconds C) Milliseconds D) Nanoseconds *Answer: C*
11. Interview Questions
Q: Are JavaScript timers perfectly accurate?
*A: No. Because JavaScript is single-threaded, if a heavy calculation is running on the main thread, the timer callback will be delayed until the main thread is clear. Therefore, setTimeout(func, 1000) means "run this in AT LEAST 1000ms", not exactly 1000ms.*
12. FAQs
Q: What if I need an interval faster than 1 millisecond?
*A: Browsers intentionally cap the minimum delay of setInterval and setTimeout (usually at 4ms). If you are building high-performance animations or games, you should use requestAnimationFrame() instead.*
13. Summary
-
setTimeout(func, delay)runs code ONCE after a delay.
-
setInterval(func, delay)runs code REPEATEDLY every delay.
- Time is always in milliseconds (1000ms = 1s).
-
Use
clearTimeout(id)andclearInterval(id)to stop them.
- Always store the returned ID in a variable if you need to stop the timer.
14. Next Chapter Recommendation
Timers and Fetch both execute code *asynchronously* (in the background, outside the main flow of execution). Managing asynchronous code using nested callbacks can become incredibly messy. In the next chapter, JavaScript Async Programming, we will master Promises and the modernasync/await syntax.