Play Sound After Delay with Howler.js
This article explains how to play audio files after a specific delay using the Howler.js library in JavaScript. You will learn how to combine Howler’s playback capabilities with native JavaScript timing functions, manage delayed execution, and handle browser autoplay restrictions effectively.
Using setTimeout with Howler.js
Howler.js does not feature a built-in delay parameter within its core
API. Instead, the standard and most effective way to play a sound after
a specific delay is by wrapping the Howler .play() method
inside a native JavaScript setTimeout() function.
Here is a basic implementation:
// Initialize the Howler sound object
const sound = new Howl({
src: ['audio/bell.mp3'],
html5: true // Use HTML5 Audio for large files
});
// Define the delay in milliseconds (e.g., 3000ms = 3 seconds)
const delay = 3000;
// Play the sound after the specified delay
setTimeout(() => {
sound.play();
}, delay);Managing and Canceling Delayed Playback
In real-world applications, you may need to cancel a scheduled sound
before it plays—for example, if a user navigates to a different page or
clicks a “stop” button. To achieve this, store the timeout ID returned
by setTimeout and pass it to clearTimeout when
needed.
const sound = new Howl({
src: ['audio/alert.mp3']
});
// Store the timeout ID
let soundTimeoutId;
function playSoundWithDelay(delayTime) {
// Clear any existing pending playback to prevent overlapping
if (soundTimeoutId) {
clearTimeout(soundTimeoutId);
}
soundTimeoutId = setTimeout(() => {
sound.play();
}, delayTime);
}
function cancelDelayedSound() {
if (soundTimeoutId) {
clearTimeout(soundTimeoutId);
console.log("Delayed sound playback canceled.");
}
}Handling Browser Autoplay Restrictions
Modern web browsers block audio from playing automatically without prior user interaction (like a click or tap). If you attempt to trigger a delayed sound immediately upon page load, the browser will likely block it.
To prevent this issue, trigger the delayed sound function inside a user-initiated event listener:
const startButton = document.getElementById('startButton');
startButton.addEventListener('click', () => {
// User interaction established; browser will allow playback after the delay
playSoundWithDelay(2000);
});