JavaScript
// Run once after a delay (milliseconds)
const id = setTimeout(() => {
console.log('3 seconds later');
}, 3000);
clearTimeout(id); // cancel before it runs
// Run repeatedly
let seconds = 0;
const timer = setInterval(() => {
seconds++;
document.getElementById('clock').textContent = seconds;
if (seconds === 10) clearInterval(timer); // stop the repeating
}, 1000);
// Real clock
setInterval(() => {
document.getElementById('clock').textContent = new Date().toLocaleTimeString();
}, 1000);- Always store the returned id so you can stop the timer.
- Pass the function itself, not its result:
setTimeout(show, 1000)is right;setTimeout(show(), 1000)runsshowimmediately. - For smooth animation and games,
requestAnimationFrame(loop)is better thansetInterval(used in 7.10). - Date helpers:
new Date(),getFullYear(),getMonth()(0 to 11),getDate(),getHours(),getTime().
Try it (DOM lab)
- To-do list: a text box and Add button; each task is an
li; clicking a task toggles strike-through; a Delete button on each item. - Countdown timer: user enters seconds, Start/Stop buttons using
setInterval. - Image slideshow: array of image paths, Next/Previous buttons, automatic change every 3 seconds.
- Dark mode toggle: a button toggling a
darkclass onbody.
Check yourself. The questions for this part are on the 7.11 Review Questions page, with answers to check your work.