Back to articles
Building a Precise Metronome in JavaScript Is Harder Than You Think

Building a Precise Metronome in JavaScript Is Harder Than You Think

via Dev.to TutorialMichael Lip

setTimeout is not accurate enough for music. A metronome needs sub-millisecond timing precision, and JavaScript's event loop cannot guarantee that. Here is how the Web Audio API solves the problem. The setTimeout problem The naive approach to a metronome: function naiveMetronome ( bpm ) { const interval = 60000 / bpm ; setInterval (() => { playClick (); }, interval ); } This does not work for music. setTimeout and setInterval are not precise. They guarantee a minimum delay, not an exact one. The JavaScript event loop processes timers only when the call stack is empty. If any other code is running (DOM updates, garbage collection, other event handlers), the timer fires late. The inaccuracy is typically 1-15 milliseconds, sometimes more. At 120 BPM, the interval between beats should be exactly 500ms. A 10ms jitter means some beats arrive at 490ms and others at 510ms. Musicians can perceive timing irregularities as small as 5ms. A metronome with 10ms jitter is unusable for practice. The W

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles