13. Timers and Intervals
Sometimes, you want your code to run **after a delay** or **every few seconds** — like showing a message later, or updating a clock. JavaScript has two powerful tools for this: `setTimeout()` and `setInterval()`.
Using setTimeout()
console.log('Waiting...');
setTimeout(() => {
console.log('3 seconds passed!');
}, 3000);`setTimeout()` runs the function **once** after the specified delay (in milliseconds). In this example, the message appears after 3 seconds.
Using setInterval()
let count = 1;
const timer = setInterval(() => {
console.log('Tick', count);
count++;
if (count > 5) {
clearInterval(timer);
console.log('Stopped!');
}
}, 1000);`setInterval()` repeats the function every given number of milliseconds until you stop it using `clearInterval()`.
Canceling a Timeout
const alertTimeout = setTimeout(() => {
alert('You stayed too long!');
}, 5000);
// Cancel it if user leaves early
clearTimeout(alertTimeout);Both `setTimeout()` and `setInterval()` return an ID. You can store it in a variable and pass it to `clearTimeout()` or `clearInterval()` to stop it.
Mini Challenge
Create a countdown from 5 to 0 that updates the page every second using `setInterval()`. When it hits 0, display “Time’s up!” and stop the timer.