setInterval: a stopwatch
Section 8: Objects and timeLesson 8.2 · ⏱ 10 min
setInterval(function, 100) repeats the function every 100 thousandths of a second, that is 10 times a second. And clearInterval stops it.
HTML
<div class="w">
<p id="time">0.0</p>
<button id="start">Start</button>
<button id="stop">Stop</button>
</div>
CSS
body { font-family: Tahoma, sans-serif; }
.w { text-align: center; }
#time { font-size: 60px; font-weight: bold; margin: 10px; }
button { font-size: 20px; padding: 8px 20px; }
JavaScript
let tenths = 0;
let timer = null;
document.getElementById("start").onclick = function () {
if (timer) return; // already running
timer = setInterval(function () {
tenths++;
document.getElementById("time").textContent = (tenths / 10).toFixed(1);
}, 100);
};
document.getElementById("stop").onclick = function () {
clearInterval(timer);
timer = null;
};
🖥️ The page in Robo Web:

🖥️ What happens on the stage?
We clicked “Start”, waited two seconds, then clicked “Stop”, and 2.1 appeared.
📌 Another example: a countdown from 5
Every second the number goes down, and at zero it stops and writes “Go!”.
HTML
<h1 id="t">5</h1>
<button id="go">Start</button>
CSS
body { font-family: Tahoma, sans-serif; }
h1 { font-size: 70px; text-align: center; }
button { font-size: 20px; padding: 8px 20px; }
JavaScript
document.getElementById("go").onclick = function () {
let n = 5;
const timer = setInterval(function () {
n--;
document.getElementById("t").textContent = n;
if (n === 0) {
clearInterval(timer);
document.getElementById("t").textContent = "Go! 🏁";
}
}, 1000);
};
🖥️ The page in Robo Web:

✍️ Practise
Try the example here: copy the code into its tabs, change it, and watch the page change.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
Test yourself
- Add a “Reset” button that takes the time back to 0.0.
🎯 Challenge yourself
Easy
After two seconds a message appears (setTimeout).
👀 Show the solution🙈 Hide the solution
HTML
<p id="m">Wait...</p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
setTimeout(function () {
document.getElementById("m").textContent = "Hello! ⏰";
}, 2000);
🖥️ The page in Robo Web:

Result: after two seconds: Hello!
Medium
A counter that goes up by itself every half second.
👀 Show the solution🙈 Hide the solution
HTML
<h1 id="n">0</h1>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
let n = 0;
setInterval(function () {
n++;
document.getElementById("n").textContent = n;
}, 500);
🖥️ The page in Robo Web:

Result: the number goes up by itself.
Hard
A clock that shows the time now and updates every second.
👀 Show the solution🙈 Hide the solution
HTML
<h1 id="clock"></h1>
CSS
body { font-family: Tahoma, sans-serif; }
h1 { font-size: 50px; }
JavaScript
function tick() {
const now = new Date();
document.getElementById("clock").textContent = now.toLocaleTimeString("en-GB");
}
tick();
setInterval(tick, 1000);
🖥️ The page in Robo Web:

Result: the clock in numbers.

