<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[MusicBun Dev Notes]]></title><description><![CDATA[MusicBun Dev Notes]]></description><link>https://musicbun.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b0d65b7c9212edcb6328702/a3f8d11a-82bd-4f95-88cf-5e006138a8a6.png</url><title>MusicBun Dev Notes</title><link>https://musicbun.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 20:44:23 GMT</lastBuildDate><atom:link href="https://musicbun.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building a metronome that doesn't drift with the Web Audio API]]></title><description><![CDATA[setInterval metronomes drift. How to schedule clicks on the Web Audio clock so a browser metronome stays on time, with code.]]></description><link>https://musicbun.hashnode.dev/building-a-metronome-that-doesn-t-drift-with-the-web-audio-api</link><guid isPermaLink="true">https://musicbun.hashnode.dev/building-a-metronome-that-doesn-t-drift-with-the-web-audio-api</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Audio API]]></category><category><![CDATA[music]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Jim Miller]]></dc:creator><pubDate>Mon, 30 Nov 2026 12:07:58 GMT</pubDate><content:encoded><![CDATA[<p>The first metronome most of us write looks like this:</p>
<pre><code class="language-js">setInterval(playClick, 60000 / bpm);
</code></pre>
<p>It sounds fine for ten seconds. Then you switch tabs, scroll a long page, or the garbage collector runs, and the clicks stumble. A musician hears a 20 ms wobble immediately.</p>
<p>The fix is an old idea from Chris Wilson's "A Tale of Two Clocks": <strong>let JavaScript plan, let the audio clock play.</strong> Here is how I built the <a href="https://musicbun.com/online-metronome">online metronome on MusicBun</a> around it.</p>
<h2>Two clocks</h2>
<ul>
<li><code>setInterval</code> and <code>requestAnimationFrame</code> run on the main thread. They are late whenever the page is busy.</li>
<li><code>AudioContext.currentTime</code> is the audio hardware's clock. Anything you schedule on it plays exactly on time, even if JavaScript is stuck.</li>
</ul>
<p>So JavaScript wakes up often, looks a little way ahead, and books every click that falls in that window at its exact time.</p>
<h2>The scheduler</h2>
<pre><code class="language-js">let next = 0, tick = 0;

function schedule() {
  const c = audio(); // one shared AudioContext
  while (next &lt; c.currentTime + 0.12) {   // look 120 ms ahead
    const beat = Math.floor(tick / sub) % beats;
    const onBeat = tick % sub === 0;
    click(next, onBeat ? (beat === 0 ? "accent" : "beat") : "sub");
    next += 60 / bpm / sub;
    tick++;
  }
}

setInterval(schedule, 25); // wake up often, but timing doesn't depend on it
</code></pre>
<p>The interval only has to fire <em>at least</em> once every 120 ms. If it fires late, the clicks it books are still on time.</p>
<h2>A click without audio files</h2>
<p>No samples needed. A sine wave with a 2 ms attack and a fast exponential decay sounds like a clean wood-block click:</p>
<pre><code class="language-js">function click(t, kind) {
  const c = audio(), o = c.createOscillator(), g = c.createGain();
  const [f, a] = kind === "accent" ? [1600, 1] : kind === "beat" ? [1050, 0.75] : [800, 0.4];
  o.frequency.value = f;
  g.gain.setValueAtTime(0, t);
  g.gain.linearRampToValueAtTime(a * vol, t + 0.002);
  g.gain.exponentialRampToValueAtTime(0.0001, t + 0.05);
  o.connect(g).connect(c.destination);
  o.start(t);
  o.stop(t + 0.06);
}
</code></pre>
<p>Higher pitch for beat one, lower and quieter for subdivisions (eighths, triplets, sixteenths). The ear picks out the bar without counting.</p>
<h2>When the tab goes to sleep</h2>
<p>Background tabs throttle timers to once a second or less. When the page comes back, <code>next</code> is far in the past, and a naive loop would fire a burst of every missed click at once.</p>
<p>So the scheduler first skips the clicks that are already late, and moves the count on by the same amount. Beat one stays where it should be:</p>
<pre><code class="language-js">if (next &lt; c.currentTime - 0.03) {
  const len = 60 / bpm / sub;
  const miss = Math.ceil((c.currentTime + 0.01 - next) / len);
  tick += miss;
  next += miss * len;
}
</code></pre>
<h2>Make the lights follow the sound, not the timer</h2>
<p>The flashing beat dots are easy to get wrong: if you light them when you <em>schedule</em> a click, they flash 120 ms early. Instead, each scheduled beat goes into a queue with its audio time, and every animation frame lights the latest one whose time has passed:</p>
<pre><code class="language-js">marks.push([next, beat]); // when scheduling

function paint() {
  const now = audio().currentTime;
  let cur = null;
  while (marks.length &amp;&amp; marks[0][0] &lt;= now) cur = marks.shift()[1];
  if (cur !== null) highlight(cur);
}
</code></pre>
<h2>Small things musicians notice</h2>
<ul>
<li><strong>Changing time signature mid-play</strong> restarts at the next bar, so you never hear a bar of 5 inside a 4/4 count.</li>
<li><strong>Changing subdivision</strong> keeps the current beat. Only the clicks in between change.</li>
<li><strong>Tap tempo</strong> averages the last 16 taps and resets after a 2-second pause, so one bad tap barely moves the result.</li>
<li><strong>Space bar</strong> starts and stops, unless focus is in a text field or on a button.</li>
</ul>
<h2>Try it</h2>
<p>The <a href="https://musicbun.com/online-metronome">free online metronome</a> has all of this: 30 to 300 BPM, six time signatures, subdivisions and tap tempo. If you don't know a song's tempo yet, the <a href="https://musicbun.com/bpm-and-key-finder">BPM and key finder</a> reads it from an audio file, also in the browser.</p>
]]></content:encoded></item></channel></rss>