Skip to content

Create a Live Coding Music App · Part 2 of 18 in the series

Part 2: A Clock That Keeps Time

JavaScript's timers are too sloppy for music. Build a clock that counts in bars, schedules notes ahead of time on the exact clock of the audio context, and keeps its place when the tempo changes. A metronome lets you hear it.

Quest objectives

  • Understand why setTimeout and setInterval cannot time music
  • Schedule notes ahead of time on the audio clock
  • Count time in cycles, so that the tempo is a separate matter
  • Change the tempo without a jump in the position
  • Play every beat exactly once, however the time is cut up
  • Show the bar and the beat on the page

The keys of part 1 play a note at the moment of a click. Music needs more than that: notes at exact moments, one after the other, with nobody clicking. This part builds the clock that does it, and a metronome to hear it by: a short click on every beat.

Why a timer is not enough

JavaScript has timers, and setInterval(tick, 500) looks like a metronome with two clicks per second. It is not one. A timer only promises that its function runs no sooner than asked. The function runs when the page has nothing else to do: after the code that is running right now, after a layout, after a repaint. So it is late by some milliseconds, and by a different amount every time. The ear is strict about rhythm: beats that are each late by a different amount sound uneven, even when the amounts are small.

Two clocks

The audio context has a clock of its own, currentTime. It counts the sound the context has put out, in seconds, and it does not care what the page is busy with. And sound can be planned on it ahead of time: the start() and stop() of the oscillator and the ramps of the envelope in part 1 all took a time. A note planned for 12.5 seconds starts at 12.5 seconds of the audio clock, whatever the page's JavaScript is doing at that moment.

So there is an exact clock that can't call any code, and a timer that calls code at inexact times. They are used together like this:

  • A timer fires often, every 25 ms.

  • Each time, it looks a short way into the future of the audio clock, 100 ms, and schedules every note that starts in the part of this window it has not covered yet. To schedule a note is to plan it on the audio clock before it is due.

Now the timer may be late. A call that came on time has covered the next 100 ms, and the call after it is due 25 ms later. As long as that one is less than 75 ms late, the next stretch of time still lies in the future when its notes are scheduled, and every note sits at its exact time. The window is the look-ahead. A longer one survives longer delays, but what is scheduled is fixed: a change of tempo, and later a change of the code, is only heard after the look-ahead has passed. 100 ms is short enough to feel immediate.

Cycles instead of seconds

Music does not count in seconds. The pulse you would tap your foot to is the beat, and the tempo says how many beats there are in a minute, in bpm (beats per minute). Beats come in groups, and one group is a bar. In this series a bar always has four beats, as in most pop and dance music.

The clock counts in cycles: one cycle is one bar. Cycle 0 is the start, 0.25 is the second beat of the first bar, 2.5 is the middle of the third bar. Everything that plays is placed in cycles, and only the clock knows how long a cycle takes: four beats, so 240 / bpm seconds, which is 2 seconds at 120 bpm. A rhythm written down in cycles is the same rhythm at any tempo.

To get from cycles to the seconds of the audio clock and back, the clock keeps an anchor: one moment of which it knows both numbers, the audio time and the cycle. From there it is a straight line: so many seconds later is so many cycles later.

Create src/clock.ts:

src/clock.ts
import { audio } from './audio.ts';

/** How often the clock looks ahead, in milliseconds. */
const INTERVAL = 25;
/** How far ahead of the audio clock notes are scheduled, in seconds. */
const LOOKAHEAD = 0.1;

/**
 * Counts time in cycles: one cycle is one bar of four beats. While it runs, it calls
 * `schedule` with every stretch of cycles that is about to be heard, each stretch once.
 */
export class Clock {
  playing = false;
  private beatsPerMinute = 120;
  /** A moment at which both clocks are known: the audio clock's seconds and our cycles. */
  private anchor = { time: 0, cycle: 0 };
  /** Everything before this cycle has been scheduled. */
  private scheduled = 0;
  private timer = 0;
  private readonly schedule: (from: number, to: number) => void;

  constructor(schedule: (from: number, to: number) => void) {
    this.schedule = schedule;
  }

  /** The length of a cycle in seconds: four beats. */
  get cycleSeconds(): number {
    return 240 / this.beatsPerMinute;
  }

  get bpm(): number {
    return this.beatsPerMinute;
  }

  set bpm(value: number) {
    // The new tempo counts from now on: move the anchor to this moment first.
    const now = audio().currentTime;
    this.anchor = { time: now, cycle: this.cycleAt(now) };
    this.beatsPerMinute = value;
  }

  /** The cycle that is playing at a time of the audio clock. */
  cycleAt(time: number): number {
    return this.anchor.cycle + (time - this.anchor.time) / this.cycleSeconds;
  }

  /** The time of the audio clock at which a cycle is reached. */
  timeAt(cycle: number): number {
    return this.anchor.time + (cycle - this.anchor.cycle) * this.cycleSeconds;
  }

  start() {
    if (this.playing) return;
    this.playing = true;
    // Start a moment from now, so the first note is not already in the past.
    this.anchor = { time: audio().currentTime + 0.05, cycle: 0 };
    this.scheduled = 0;
    this.timer = window.setInterval(() => this.tick(), INTERVAL);
    this.tick();
  }

  stop() {
    this.playing = false;
    window.clearInterval(this.timer);
  }

  private tick() {
    const until = this.cycleAt(audio().currentTime + LOOKAHEAD);
    if (until <= this.scheduled) return;
    this.schedule(this.scheduled, until);
    this.scheduled = until;
  }
}
  • cycleAt() and timeAt() are the same line read in both directions: from a time to a cycle, and from a cycle to a time.

  • start() sets the anchor: cycle 0 is 50 ms from now. Without this margin the first note would be due at the very moment it is scheduled, and would be in the past before its nodes are made. Then it starts the timer and calls tick() right away, so that the first stretch does not wait 25 ms.

  • tick() asks which cycle will be reached 100 ms from now, hands the stretch from scheduled to there to the function the clock was created with, and remembers how far it has come.

  • stop() only stops the timer. Notes that are scheduled already still play, which is 100 ms of music at most.

The contract of schedule

The clock makes one promise to the function it calls: every stretch of cycles comes exactly once. Each call begins where the one before it ended, from 0 on, with no gap and no overlap. How long a stretch is, is not fixed: about 25 ms of music if the timer is on time, more if it was late.

In return, the function has to play everything that starts inside the stretch, with from counted in and to counted out. If every stretch is treated like that, each note falls into exactly one of them, however the time is cut up.

Changing the tempo

The setter of bpm does one thing before it stores the new tempo: it moves the anchor to now. Numbers show why. After one minute at 120 bpm the music is at cycle 30. If the tempo changed to 60 bpm with the anchor still at the start, cycleAt() would count the whole minute at the new tempo and answer with cycle 15: the music would jump back fifteen bars. With the anchor moved to this moment first, the past stays as it was played, and only what comes after it runs at the new speed.

The check at the top of tick() belongs to this. Right after the tempo went down, 100 ms ahead are fewer cycles than before, and until can lie before what is scheduled already. Then there is nothing to do until the clock has caught up.

A metronome

The page gets a Play button, a display for the position and a slider for the tempo. In index.html, replace the <header> and the <main> element. The keys of part 1 go, and the hint changes:

index.html
<header>
  <strong class="name">loopcode</strong>
  <button id="play">▶ Play</button>
  <span id="position" class="position">1.1</span>
  <label class="tempo">
    <input id="bpm" type="range" min="60" max="180" value="120" />
    <span id="bpm-value">120</span> bpm
  </label>
</header>
<main class="stage">
  <p class="hint">Press Play, then move the tempo.</p>
</main>

In src/main.ts, add an import of Clock from ./clock.ts. beep() stays as it is. Remove everything below it, the scale and the keys, and create the clock there:

src/main.ts
/** A metronome: a click on every beat, a higher one on the first beat of a bar. */
const clock = new Clock((from, to) => {
  // Beats are quarters of a cycle. Take every beat that starts inside the stretch.
  for (let beat = Math.ceil(from * 4); beat < to * 4; beat += 1) {
    beep(beat % 4 === 0 ? 84 : 72, clock.timeAt(beat / 4), 0.08);
  }
});

A beat is a quarter of a cycle, so beat number n is at cycle n / 4. The loop begins with the first whole beat at or after from, which is what Math.ceil() finds, and goes on as long as the beat lies before to.

Take a beat right on a border: beat 1 at cycle 0.25, and two stretches that meet there. For the stretch from 0.2375 to 0.25 the loop begins at Math.ceil(0.95), which is 1, and 1 is not less than 1: nothing plays. For the stretch from 0.25 to 0.2625 it begins at Math.ceil(1), which is 1 again, and 1 is less than 1.05: the beat plays. It plays once, in the stretch that begins with it. With <= in place of < it would play twice, once in each of the two stretches.

timeAt() turns the beat's cycle into a time of the audio clock, and this is what the time parameter of beep() was made for. The first beat of a bar is note 84, the others are note 72, one octave below, and each lasts 0.08 seconds: a short click.

Below the clock, the Play button starts and stops it:

src/main.ts
const play = document.querySelector<HTMLButtonElement>('#play')!;
play.addEventListener('click', async () => {
  await audio().resume();
  if (clock.playing) clock.stop();
  else clock.start();
  play.textContent = clock.playing ? '■ Stop' : '▶ Play';
  play.classList.toggle('on', clock.playing);
});

The button's text and its class on follow clock.playing. The rule for button.on has been in the styles since part 1 and turns the button orange. Then the slider, which sets the tempo while the clock runs:

src/main.ts
const bpm = document.querySelector<HTMLInputElement>('#bpm')!;
const bpmValue = document.querySelector<HTMLSpanElement>('#bpm-value')!;
bpm.addEventListener('input', () => {
  clock.bpm = Number(bpm.value);
  bpmValue.textContent = bpm.value;
});

The input event comes with every move of the slider, not only when it is let go.

Where the music is

The display shows the bar and the beat, both counted from 1, as musicians do: 1.1 is the first beat of the first bar, 3.2 the second beat of the third. Add at the end of the file:

src/main.ts
/** Shows where the music is, as bar.beat, once per frame. */
const position = document.querySelector<HTMLSpanElement>('#position')!;
function draw() {
  const cycle = clock.playing ? Math.max(0, clock.cycleAt(audio().currentTime)) : 0;
  position.textContent = `${Math.floor(cycle) + 1}.${Math.floor((cycle % 1) * 4) + 1}`;
  requestAnimationFrame(draw);
}
draw();

requestAnimationFrame() calls draw() again before the browser paints its next frame. The function counts nothing by itself. It asks the clock which cycle the audio clock has reached, so the display can't drift away from the sound. Math.max(0, …) is for the first 50 ms after Play, in which the cycle is still below 0. While the clock is stopped, the display stays at 1.1.

In src/style.css, remove the two rules at the end, .keys and .keys button. Add three rules for the new elements of the header, after the rules for button and before .stage:

src/style.css
.position {
  min-width: 4ch;
  color: var(--lilac);
  font-weight: bold;
}

.tempo {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-left: auto;
  color: var(--muted);
}

.tempo input {
  width: 110px;
  accent-color: var(--orange);
}

Try it

Press Play. A click sounds on every beat, two per second at 120 bpm, and the first of every four is an octave higher. The display counts along: 1.1, 1.2, 1.3, 1.4, 2.1. Move the slider while it plays: the clicks get faster or slower right away, and the count goes on from where it is, without a jump. Press Stop, and the display is back at 1.1. The next Play starts at the first bar again.

  • Set LOOKAHEAD in src/clock.ts to 1. The metronome sounds as before. But move the slider: the clicks that are scheduled already, now a whole second of them, keep their old times. The new tempo comes late, and the beat stumbles where the old clicks and the new ones meet. After Stop the scheduled clicks still play, too. Set it back to 0.1.

  • Make the metronome count sixteenths, four to a beat: in the loop, write 16 instead of 4 in from * 4, to * 4, beat % 4 and beat / 4. At 120 bpm that is eight clicks per second, with the higher one at the start of each bar, and they are as even as the beats were. Put the 4 back afterwards.

A clock and a click are not much of a band. The next part gives the clock a drum machine to play.

The app at the end of part 2. Play starts the metronome, and the slider changes the tempo while it runs.
Open in a new tab

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.