Skip to content

EZ Web Audio / audioContextAwareTimeout

Function: audioContextAwareTimeout()

audioContextAwareTimeout(audioContext): object

Defined in: utils/timeout.ts:50

Create AudioContext-aware setTimeout and clearTimeout functions that use audioContext.currentTime and requestAnimationFrame instead of native timers.

Browser tabs that are backgrounded or hidden can have native setTimeout throttled to fire as infrequently as once per second, causing visual beat indicators and other UI timing to drift out of sync with audio playback. This utility avoids that drift by driving all timer checks through requestAnimationFrame and measuring elapsed time using audioContext.currentTime, which always advances at audio-clock speed regardless of tab visibility.

When to use: Any UI timing that needs to stay in sync with audio playback — visual beat indicators, countdowns, progress bars, or any scheduled UI update tied to musical timing.

Graceful fallback: If no audioContext is provided the function falls back to native window.setTimeout/window.clearTimeout and logs a warning. This keeps code working even if audio has not been initialized yet.

Parameters

audioContext

The AudioContext (or BaseAudioContext) driving playback

AudioContext | BaseAudioContext | AudioContextMock

Returns

object

An object with setTimeout and clearTimeout that mirror the native API

clearTimeout()

clearTimeout: (id) => void

Parameters

id

number

Returns

void

setTimeout()

setTimeout: (fn, delayMillis) => number

Parameters

fn

() => void

delayMillis

number

Returns

number

Example

typescript
import { getAudioContext, audioContextAwareTimeout } from 'ez-web-audio'

// Get the shared AudioContext
const ctx = await getAudioContext()

// Create audio-aware timer functions
const { setTimeout, clearTimeout } = audioContextAwareTimeout(ctx)

// Use just like native timers — they stay in sync with audio even in background tabs
const id = setTimeout(() => {
  flashBeatIndicator()
}, 500)

// Cancel if needed
clearTimeout(id)