How to Play Sound Only Once in Howler.js
This article explains how to prevent a sound from playing multiple times or overlapping in Howler.js, even if the playback trigger is activated repeatedly. You will learn how to implement state checks and utilize Howler’s built-in methods to ensure a clean, single-play audio experience.
When building interactive web applications, rapid user interactions—like double-clicking a button—can trigger the same sound multiple times simultaneously, resulting in unpleasant, overlapping audio. Depending on your project’s needs, “playing once” can mean preventing overlapping playback while the sound is already running, or restricting the sound to play only a single time ever.
Method 1: Prevent Overlapping Playback (Check if Already Playing)
If you want to allow the sound to be played again later, but want to
block new playbacks if the sound is currently playing, use the
.playing() method. This is ideal for UI button clicks.
// Initialize the Howler sound
const clickSound = new Howl({
src: ['click.mp3']
});
// Function to trigger the sound safely
function triggerSound() {
// Check if the sound is not already playing
if (!clickSound.playing()) {
clickSound.play();
}
}Method 2: Play Only Once Ever (State Flag)
If you want the sound to play exactly once per page load (such as an introductory sound or a one-time achievement alert) and never trigger again, use a simple boolean flag.
const achievementSound = new Howl({
src: ['success.mp3']
});
let hasPlayed = false;
function playAchievement() {
if (!hasPlayed) {
achievementSound.play();
hasPlayed = true; // Set flag to true so it cannot be triggered again
}
}Method 3: Using the
once Event Listener
If you want to execute a specific action only the first time a sound
finishes playing, Howler.js provides a .once() event
binder. This is useful for self-destructing event triggers.
const sound = new Howl({
src: ['audio.mp3']
});
// This event listener will only run once, then remove itself
sound.once('end', function() {
console.log('The sound has finished playing for the first time.');
});
sound.play();