Tone.js Schedule Callback on Every Transport Beat
This article explains how to schedule a callback function to execute
on every beat of the Tone.js transport. You will learn how to use the
scheduleRepeat method to trigger events at regular musical
intervals, enabling precise, time-synced audio events in your web
applications.
To schedule a function to run repeatedly on every beat, you use the
Tone.Transport.scheduleRepeat method. This method takes a
callback function and a time interval as its primary arguments. In
standard musical notation, a single beat in 4/4 time is represented as a
quarter note, which is denoted as "4n" in Tone.js time
syntax.
Here is how to set up and start the repeating callback:
import * as Tone from 'tone';
// 1. Define the callback function
const onBeat = (time) => {
// Insert your audio event here
console.log("Beat triggered at transport time:", time);
};
// 2. Schedule the callback to run every quarter note ("4n")
const eventId = Tone.Transport.scheduleRepeat(onBeat, "4n");
// 3. Start the Transport to begin playback
Tone.Transport.start();Key Considerations
- The
timeParameter: The callback function automatically receives atimeparameter. To ensure sample-accurate, drift-free audio playback, always pass thistimeargument to your synth triggers (for example,synth.triggerAttackRelease("C4", "8n", time)). - Adjusting the Interval: The second argument of
scheduleRepeatdefines the frequency of the callback. If you want to trigger events on eighth notes instead of quarter notes, change"4n"to"8n". For a callback on every measure, use"1m". - Stopping the Event: The
scheduleRepeatmethod returns a unique ID number. If you need to stop the callback from firing without stopping the entire Transport timeline, you can cancel it by callingTone.Transport.clear(eventId).