Running Code Later, and Again

setTimeout(fn, ms) runs a function once, after a delay. setInterval(fn, ms) runs it over and over, every ms milliseconds. Both hand back an id; keep it in a variable, because clearTimeout(id) and clearInterval(id) are the only way to stop them.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

update draws the time once, and setInterval keeps calling it. It runs four times a second rather than once, so the display changes within a quarter of a second of the real second changing, instead of lagging up to a whole second behind.

Counting ticks drifts. A countdown that subtracts 1 every 1000 milliseconds slowly falls behind, because an interval is never exactly on time, and a browser slows timers in a tab you aren't looking at to once a second or less.

The fix is to remember when it should end, endAt = Date.now() + seconds * 1000, and have each tick work out what's left: (endAt - Date.now()) / 1000. However late a tick runs, it shows the right answer.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

Start records the moment the countdown should end and starts a ticker. Every tick works out what's left from the clock, so a late tick can't make it drift. Clearing any old ticker before starting means pressing Start twice doesn't leave two of them running.

YOUR TURN · WEB PAGE
Your turn → Turn Stop into Pause: when pressed, save how many seconds are left in a variable. Then add a Resume button that sets endAt to now plus the saved seconds and starts the ticker again.
loading editor…

Syntax has to be exact. Every quote, bracket, brace and parenthesis needs its partner, and every HTML tag you open needs closing. One slip and the script won't run; the message under the page will say where.

One more event belongs with timers: visibilitychange fires when the tab is hidden or shown again, and document.hidden says which. Calling your tick function the moment the tab comes back means the display is right immediately, instead of after the browser's slowed-down timer next fires.

◈ Graded Build

Start counts down from 3 seconds, showing 00:03, 00:02, 00:01, then Done. Pause freezes the display where it is. Use an end timestamp, not a counter, so the countdown can't drift.

Checked by using your page: clicking, typing and waiting, then reading what changed. 3 visible and 1 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back