My first timer was setInterval decrementing a number every second, with new Audio('beep.mp3').play() at zero. The first user feedback I got: "I switched tabs to read the rules, came back, and the timer was several seconds behind."
That's not a bug, it's spec behavior. Chrome throttles timers in background tabs, worst case down to once a minute. And setInterval(fn, 1000) isn't precise even in the foreground — it's "at least 1000ms," and drifts when the main thread is busy.
I moved to Web Audio. The core idea: decouple the UI countdown from the sound event. The UI still uses requestAnimationFrame to compute remaining time (based on performance.now(), not by counting setInterval ticks), while the end beep is scheduled on the audio timeline:
const ctx = new AudioContext();
async function startTimer(seconds) {
if (ctx.state === 'suspended') await ctx.resume();
const endAt = ctx.currentTime + seconds;
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.frequency.value = 880;
gain.gain.setValueAtTime(0, endAt);
gain.gain.linearRampToValueAtTime(0.3, endAt + 0.01);
gain.gain.exponentialRampToValueAtTime(0.001, endAt + 0.4);
osc.connect(gain).connect(ctx.destination);
osc.start(endAt);
osc.stop(endAt + 0.5);
const raf = () => {
const left = Math.max(0, endAt - ctx.currentTime);
render(left);
if (left > 0) requestAnimationFrame(raf);
};
requestAnimationFrame(raf);
}
AudioContext.currentTime is a hardware audio clock, unaffected by main-thread jank. Even if the tab is throttled in the background, osc.start(endAt) still fires on time in the audio thread. When the user comes back, the beep already happened, and the UI computes the remaining time from ctx.currentTime and shows 0.
Where I have to be honest
If you just need a tick every second and ±200ms precision, <audio> plus a performance.now()-corrected loop is fine. Web Audio actually solves two things: on-time firing under background throttling, and controllable mobile autoplay. Don't treat it as "the more advanced API."
The iOS trap: AudioContext is suspended before a user gesture. I had to call resume() inside the click handler of the "start timer" button. Early on I put resume() outside the gesture callback in an async chain, and some users reported "no sound on the first tap, sound only on the second." The gesture context was lost. Worth remembering.
You can watch the timer behavior yourself at sketchwordgen.com — switch tabs mid-countdown and see what happens when you come back.
Top comments (0)