🟨 JavaScript tutorial for beginners · Class 8 · Lesson 14 of 18 · Free
Timers & Intervals – Run Code Later and Again and Again
⏱ About 30 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Run code after a delay with setTimeout()
- Repeat code with setInterval() and stop it with clearInterval()
- Build a countdown and a stopwatch that update a web page
The pressure cooker whistles after a few minutes. The school bell rings every 40 minutes. Real life is full of "do this later" and "do this again and again". In this lesson, you teach JavaScript to wait and repeat, and you build a countdown and a stopwatch.
How does setTimeout work in JavaScript?
`setTimeout(function, delay)` means "run this function later". The delay is in **milliseconds** (ms). 1000 ms = 1 second.
The surprise: JavaScript does **not** stop and wait. It puts the job aside, runs the next lines, and comes back when the time is up.
Watch the order of the lines in the output below. "Do homework meanwhile" comes before the tiffin!
▶console.log("🍱 Mom starts packing tiffin");23setTimeout(() => {4 console.log("✅ Tiffin is ready!");5}, 1000);67console.log("📚 Do homework meanwhile");
No variables yet.
▌✏️ Change this code and run it yourself
🍱 Mom starts packing tiffin📚 Do homework meanwhile✅ Tiffin is ready!
💡 Try it: change 1000 to 2000. The program takes longer, but the order stays the same.
Why does setTimeout with 0 still run last?
Even `setTimeout(fn, 0)` does not run at once. A timer job always waits until all the normal lines have finished.
When several timers are waiting, the one with the **smaller delay** runs first, not the one written first.
Think of it like a queue at the canteen. You must first finish your current work, then the timers are served by their time.
▶console.log("1. Start");23setTimeout(() => console.log("4. After 600 ms"), 600);4setTimeout(() => console.log("3. After 0 ms"), 0);56console.log("2. End of normal code");
No variables yet.
▌✏️ Change this code and run it yourself
1. Start2. End of normal code3. After 0 ms4. After 600 ms
How do I repeat code with setInterval in JavaScript?
`setInterval(function, delay)` runs the function again and again, every `delay` ms. It never stops by itself!
So it gives you an **id** number. Keep it in a `const`, and call `clearInterval(id)` when you want it to stop.
Here is a rocket countdown. Every half second the number goes down. At 0, we stop the interval.
▶let count = 3;23const id = setInterval(() => {4 if (count > 0) {5 console.log(count);6 count--;7 } else {8 console.log("🚀 Lift off!");9 clearInterval(id);10 }11}, 500);
No variables yet.
▌✏️ Change this code and run it yourself
321🚀 Lift off!
💡 Try it: start from 5 instead of 3.
How do I cancel a timer before it runs?
`setTimeout` also gives an id. `clearTimeout(id)` cancels the job if it has not run yet.
This is useful for things like an alarm you switch off, or a popup that should not appear if the user already clicked.
Alarm switched off. It is Sunday!💧 Drink some water
How do I build a countdown timer on a web page?
Now let the timer change the page, using what you learnt in Lesson 4 (DOM). Every second, we write the new number into the heading.
We also turn off the button while it counts, so nobody starts two intervals at once. Two intervals together would count twice as fast!
Click **Start** and watch.
📄 HTML of the page (tap to see / edit)
Press Start to begin the countdown
How do I make a stopwatch with start and stop buttons in JavaScript?
A stopwatch needs an interval that starts on one button and stops on another. We keep the id in a `let` variable outside, so both buttons can use it.
We count tenths of a second (every 100 ms), then show them as seconds with `toFixed(1)`.
Use it to time how fast you can say the 7 times table!
📄 HTML of the page (tap to see / edit)
Press Start, then Stop
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
console.log("A");
setTimeout(() => console.log("B"), 0);
console.log("C");Question 2. What does this print?
let n = 0;
const id = setInterval(() => {
n++;
console.log(n);
if (n === 3) clearInterval(id);
}, 100);Question 3. What does this print?
setTimeout(() => console.log("first"), 300);
setTimeout(() => console.log("second"), 100);🧩 Your challenge
Make a **study break timer**. Print a round number every 300 ms for 4 rounds of study, then print the break message and stop the interval. Expected output: ``` 📖 Study round 1 📖 Study round 2 📖 Study round 3 📖 Study round 4 ☕ Break time! Stand up and stretch. ```
📖 Study round 1 📖 Study round 2 📖 Study round 3 📖 Study round 4 ☕ Break time! Stand up and stretch.
⚠️ Common mistakes (and how to fix them)
❌ Wrong
function ring() {
console.log("🔔 Bell rings!");
}
setTimeout(ring(), 2000);
console.log("Class has started");No error, but the bell rings at once, before "Class has started". It does not wait 2 seconds.
✅ Right
function ring() {
console.log("🔔 Bell rings!");
}
setTimeout(ring, 2000);
console.log("Class has started");ring() with brackets calls the function at once. Give setTimeout the function name without brackets, so it can call it later.
❌ Wrong
setTimeout(() => {
console.log("Time to revise!");
}, 3);No error, but the message appears almost at once (after 3 milliseconds), not after 3 seconds.
✅ Right
setTimeout(() => {
console.log("Time to revise!");
}, 3000);The delay is in milliseconds, not seconds. 3 seconds is 3000 ms.
❌ Wrong
let ticks = 0;
setInterval(() => {
ticks++;
console.log("tick", ticks);
}, 1000);No error message — but it never stops. It keeps printing tick 1, tick 2, tick 3… forever.
✅ Right
let ticks = 0;
const id = setInterval(() => {
ticks++;
console.log("tick", ticks);
if (ticks === 3) clearInterval(id);
}, 1000);setInterval never stops by itself. Save its id and call clearInterval(id) when you are done.
📌 Remember
- setTimeout(fn, ms) runs fn once, after ms milliseconds. 1000 ms = 1 second.
- JavaScript does not wait for a timer: the next lines run first.
- setInterval(fn, ms) runs fn again and again, until you call clearInterval(id).
- clearTimeout(id) cancels a timer that has not run yet.
- Pass the function name without brackets: setTimeout(ring, 1000).
Finished the quiz and the challenge?
Questions students ask
What is the difference between setTimeout and setInterval?
setTimeout runs a function one time, after a delay. setInterval runs a function again and again, with the same gap each time, until you stop it with clearInterval.
Is the setTimeout delay exact?
Not exactly. The delay is the shortest wait. If the browser is busy, the function may run a little later. That is why timers are fine for games and clocks, but not for exact science measurements.
Why does JavaScript not wait for setTimeout?
JavaScript does one thing at a time. If it waited, the whole page would freeze and buttons would not work. So it keeps the timer job aside and runs it when the time is up.
How do I stop setInterval in JavaScript?
Save the number it returns: const id = setInterval(...). Then call clearInterval(id) when you want it to stop, for example when a count reaches 0.