JavaScript Timers – setTimeout() vs setInterval()
JavaScript provides two main timer functions to run code after a delay or repeatedly at intervals: setTimeout() and setInterval().
1. setTimeout() - Run Once After a Delay
The setTimeout() method executes a function once after a specified number of milliseconds.
Syntax:
setTimeout(function, delayInMilliseconds, param1, param2, ...);
Example:
setTimeout(() => {
console.log("This message appears after 2 seconds!");
}, 2000);
Output (after 2 seconds):
This message appears after 2 seconds!
2. setInterval() - Run Repeatedly at Intervals
The setInterval() method calls a function repeatedly every set number of milliseconds.
Syntax:
setInterval(function, intervalInMilliseconds, param1, param2, ...);
Example:
setInterval(() => {
console.log("This message appears every 1 second!");
}, 1000);
Output:
This message appears every 1 second!
(Repeated every second)
3. Stopping the Timers
Both methods return a timer ID that you can use to stop them.
Stop setTimeout with clearTimeout():
const timeoutId = setTimeout(() => {
console.log("You won't see this if cleared");
}, 3000);
clearTimeout(timeoutId); // Cancels the timeout
Stop setInterval with clearInterval():
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count === 5) {
clearInterval(intervalId); // Stop after 5 counts
}
}, 1000);
4. Real-World Use Cases
setTimeout():
- Delayed popups or messages
- Splash screen delays
- Executing animations after a wait
setInterval():
- Clocks or timers
- Auto-updating dashboards
- Repeating animations