Timers (setTimeout & setInterval)
Sometimes you want code to run after a delay, or repeatedly over time. JavaScript provides built-in timer functions.
setTimeout
Runs a function ONCE after a specified delay in milliseconds.
setTimeout(() => {
console.log("2 seconds have passed!");
}, 2000);
setInterval
Runs a function REPEATEDLY, waiting a specific time between each run. You can stop it using clearInterval.
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(count);
if (count === 5) {
clearInterval(intervalId); // Stops the timer
}
}, 1000);
Practice
Challenge 1: Create a countdown that prints 3, 2, 1, then "Go!", one second apart.