Timers run code later or repeatedly.
setTimeout — run once after a delay
setTimeout(() => alert('3 seconds passed'), 3000);
Time is in milliseconds (1000 ms = 1 second).
setInterval — run again and again
const id = setInterval(() => console.log('tick'), 1000);
Stop a timer
Both return an id. Pass it to clearTimeout(id) or clearInterval(id).
Uses
Countdowns, clocks, slideshows, auto-saving, hiding a message after a few seconds.
Example
Example — Countdown timer
HTML
<h1 id="time">10</h1>
<button id="start">Start</button>
<button id="stop">Stop</button>
<script>
let seconds = 10;
let timer = null;
const show = () => document.getElementById('time').textContent = seconds;
document.getElementById('start').onclick = () => {
if (timer) return;
timer = setInterval(() => {
seconds--;
show();
if (seconds === 0) {
clearInterval(timer);
timer = null;
document.getElementById('time').textContent = 'Time up!';
}
}, 1000);
};
document.getElementById('stop').onclick = () => {
clearInterval(timer);
timer = null;
};
</script>