Benchmark the accuracy of various timers available in JavaScript. Press the START button to run the benchmark. The benchmark will measure n seconds and measure its accuracy. When benchmarking, keep in mind that JavaScript execution speed differs between foreground and background. If you want to check the accurary in the background, activate another tab within 1 second after pressing the test button.

Result:

method1sec error2sec error
setTimeout
setInterval (10)
setInterval (100)
AudioBufferSourceNode
OscillatorNode
ConstantSourceNode
requestAnimationFrame

Conclusion

setTimeout & setInterval

Suitable for general use. Less accurate in inactive tabs (ref: MDN).

requestAnimationFrame

Should run in active tabs.

AudioBufferSourceNode

It has lower accurary at initial startup than OscillatorNode and ConstantSourceNode. However, from the second time onwards, the accuracy is higher than theirs.

OscillatorNode & ConstantSourceNode

Suitable for audio playback or when you need a high-precision timer in inactive tabs. It is less accurate than setTimeout and setInterval in active tabs.

Tips for Safari

  • AudioScheduledSourceNode needs to be connected to the destionation
  • AudioBufferSourceNode requires an AudioBuffer
  • Web Audio API is forcibly "suspended" when entering the background
  • Web Audio API cannot be resumed while in the background
  • Web Audio API requires resume() when returning to the foreground