How to Cancel Tone.js Transport Events
This article explains how to clear or cancel specific scheduled
events from the Tone.js Transport timeline. You will learn
how to capture unique event identifiers during the scheduling process
and use the Transport.clear() method to remove them,
ensuring precise control over your interactive audio applications.
To cancel a specific scheduled event in Tone.js, you must capture the
unique ID returned when the event is initially created and then pass
that ID to the Tone.Transport.clear() method.
Step 1: Capture the Event ID
When you schedule an event using
Tone.Transport.schedule(),
Tone.Transport.scheduleRepeat(), or
Tone.Transport.scheduleOnce(), the function returns a
unique integer ID. You must store this ID in a variable to reference it
later.
// Schedule an event and store its ID
const eventId = Tone.Transport.schedule((time) => {
// Your audio trigger or callback logic here
synth.triggerAttackRelease("C4", "8n", time);
}, "2m"); Step 2: Clear the Event Using the ID
To remove the scheduled event from the timeline, pass the stored ID
to Tone.Transport.clear(). Once cleared, the callback will
no longer trigger when the Transport reaches that position.
// Cancel the specific event using its ID
Tone.Transport.clear(eventId);Alternative: Canceling Multiple Events after a Specific Time
If you want to clear all events scheduled after a specific timeline
position rather than a single specific event, use
Tone.Transport.cancel().
Passing a time argument to cancel() will remove all
events scheduled at or after that time. If no argument is provided, it
defaults to 0, clearing all scheduled events from the
entire timeline.
// Clear all events scheduled after the 4th measure
Tone.Transport.cancel("4m");
// Clear absolutely everything from the Transport timeline
Tone.Transport.cancel();