I am experimenting with JavaScript’s async functions and the await keyword. I have created two promise functions to play an mp3 and to wait using setTimeout, and an async function to call them using the await keyword.
I was having trouble after playing a long mp3, and found that the same problem occurs if I wait too long. If I play a sound, wait for a while, then try to play a second sound, the second sound won’t play if the wait is too long, just under 3000 milliseconds. This is in Firefox, while Safari appears to be OK with this.
I have included a snippet, but the snippet works well, even in Firefox. I have included the same code online at https://resources.webcraft101.com/await-not-working.html and here it fails properly.
I cannot work out whether the problem lies with the function to play the sound, or something else.
function wait(delay) {
return new Promise(function(resolve,reject) {
setTimeout(()=>{
resolve();
},delay);
});
};
function playSound(sound) {
return new Promise(function(resolve,reject) {
var audio=new Audio(sound);
audio.addEventListener('ended',()=>{
resolve();
});
audio.play();
});
};
async function playAsync() {
await playSound('https://resources.webcraft101.com/sounds/drums.mp3');
console.log('after drums');
await wait(5000); // 2992 kills it
console.log('after wait');
await playSound('https://resources.webcraft101.com/sounds/cuckoo.mp3');
console.log('after cuckoo');
}
document.querySelector('button#play-async').onclick=playAsync;
<button id="play-async">Async</button>