Vanilla JavaScript Projects

Project 85, Content and data

Countdown Timer Kit

Four timers websites need again and again, all accurate to the second, even when the tab has been in the background for a while.

09:5902:14
Main API
Date + performance.now
Sound
Web Audio API
Dependencies
None
Your browser
Checking

Pick a timer

Set an event date, watch the sale timer, start the kitchen timer with a sound at the end, or use the stopwatch with laps.

How it works

  1. Count to a target timeTimers store the end time, not a counter. Each tick works out what is left from the clock, so background tabs and slow devices never drift.
  2. Time zones done rightThe event countdown converts the chosen date and zone into an exact moment, so everyone sees the same countdown wherever they are.
  3. Sound without filesThe kitchen timer makes three beeps with the Web Audio API. The audio context starts on the Start click, which browsers require.
let end = performance.now() + minutes * 60000;
function tick() {
  const left = Math.max(0, end - performance.now());   // no drift
  display.textContent = format(left);
  if (left === 0) beep(); else requestAnimationFrame(tick);
}
function beep() {
  const ctx = new AudioContext(), osc = ctx.createOscillator();
  osc.frequency.value = 880; osc.connect(ctx.destination);
  osc.start(); osc.stop(ctx.currentTime + 0.3);
}