In this video, you built a countdown for Sam’s recipe steps that keeps the right time even when the page is busy, and wrapped it in a factory that gives every step its own timer.
Key Points
- Counting ticks drifts. A countdown that takes one second off on every
setInterval()tick trusts each tick to come on time. While JavaScript is busy, the browser can’t interrupt it. When it’s free, one late tick runs and the rest are dropped, never made up. - Dropped ticks never come back. A late tick only makes the line stale for a moment, but every dropped tick costs the countdown a second for good. In the video, a ten-second countdown with a three-second busy stretch dropped two ticks and reached zero after about twelve seconds.
- Background tabs make it worse. In a tab in the background, the browser runs timers even less often, so a tick-counting countdown falls further behind still.
- Count down from a deadline. Note the deadline once,
Date.now()plus the duration, and on every tick work out the time left as the deadline minusDate.now().Math.ceil()rounds the milliseconds up to whole seconds, so a little under nine seconds shows as9. - A busy page still delays a redraw, but every redraw is right. With the same busy stretch, the deadline version stopped at
8, jumped to5(four and a half seconds, rounded up) when the page was free, and in the video’s run reached zero right on the deadline. - The deadline can’t make a tick come on time. That was this run’s result. The countdown finishes on the first tick at or after the deadline, so a page that’s busy at that moment finishes late too. The deadline keeps the number right, but it can’t make a tick come on time. Once the time is up, the tick sets it to zero, so the line never shows a negative number.
- The rule: keep the deadline, and work out what to show from
Date.now(). The tick only decides when to redraw. - One timer per step.
makeStepTimer()is a factory: each call adds its own line to the page and keeps its own time left, deadline and interval ID in its own box.pause()takes one last reading to bring the time left up to date, then clears the interval.start()sets the deadline to now plus the time left, so a restart picks up where the pause left off. - Start and pause guard themselves.
start()checks the interval ID and the time left first, so it does nothing when its timer is already running or finished.pause()does nothing when nothing’s running. When the tick stops at zero, it sets the interval ID back toundefined, so the ID always tells you whether the timer is running.
The Code
Open Sam’s recipe box through Live Preview at http://127.0.0.1:3000/recipes/index.html, open the Console, and type each entry with Shift+Enter between its lines. The timers are toys that count seconds instead of minutes. The first entry sets up a stand-in for a busy page and a line for the countdown: