JavaScript timers allow you to execute code after a delay or repeat code at regular intervals. They are commonly used for animations, notifications, auto-refresh features, countdowns, and real-time updates.
JavaScript provides two main timer functions:
The setTimeout() function executes a function one time after a specified number of milliseconds.
setTimeout(function, delay);
setTimeout(() => {
console.log("Hello after 2 seconds!");
}, 2000);
const timerId = setTimeout(() => {
console.log("This will not run");
}, 3000);
clearTimeout(timerId);
setInterval(function, interval);
setInterval(() => {
console.log("Runs every second");
}, 1000);
Use clearInterval() to stop the interval.
const intervalId = setInterval(() => {
console.log("Running...");
}, 1000);
clearInterval(intervalId);
let count = 5;
const countdown = setInterval(() => {
console.log(count);
count--;
if (count < 0) {
clearInterval(countdown);
console.log("Time's up!");
}
}, 1000);
| Feature | setTimeout | setInterval |
|---|---|---|
| Execution | Runs once | Runs repeatedly |
| Use Case | Delayed action | Repeated task |
| Stop Method | clearTimeout() | clearInterval() |
| Example | Popup after delay | Live clock |
setInterval(fn, 1000);
function repeat() {
fn();
setTimeout(repeat, 1000);
}
repeat();