JavaScript timers allow scheduling code execution after a delay or repeatedly at intervals. The two main timer functions are setTimeout and setInterval.

setTimeout
setTimeout runs a function once after a specified delay (in milliseconds).
- Syntax:
setTimeout(callback, delay) - callback: Function to run after delay
- delay: Time in milliseconds to wait
📌 Deep Dive: Using setTimeout
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);
setInterval
setInterval runs a function repeatedly at fixed intervals (in milliseconds) until stopped.
- Syntax:
setInterval(callback, interval) - callback: Function to run repeatedly
- interval: Time in milliseconds between runs
📌 Deep Dive: Using setInterval
const intervalId = setInterval(() => {
console.log("Repeated every second");
}, 1000);
// To stop the interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
console.log("Interval stopped");
}, 5000);
💡 Important:
Both setTimeout and setInterval return a unique timer ID. Use clearTimeout(id) or clearInterval(id) to cancel timers before they run.
| Feature | setTimeout | setInterval |
|---|---|---|
| Runs | Once after delay | Repeatedly every interval |
| Return value | Timeout ID | Interval ID |
| Cancel function | clearTimeout(id) | clearInterval(id) |
| Use case | One-time delay | Periodic repeated actions |
⚠️ Common Pitfall
Using setInterval can cause overlapping calls if the callback takes longer than the interval. Consider using recursive setTimeout for better control.
Example of recursive setTimeout for repeated tasks:
📌 Deep Dive: Recursive setTimeout for intervals
function repeatTask() {
console.log("Task runs every 1 second, safely");
setTimeout(repeatTask, 1000);
}
repeatTask();
💡 Summary
setTimeout: run once after delaysetInterval: run repeatedly at intervals- Use
clearTimeoutorclearIntervalto stop timers - Recursive
setTimeoutcan offer better control for repeated tasks
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which function runs a callback once after a delay?
Question 2 of 2
How do you stop a running interval?
Loading results...