I am using ended event in JavaScript to know when the sound ends playing. In Chrome, if the alert box is open at the time the sound ends, the event code will be executed after the box is closed. But, in that case, the event code is often called twice, followed by a DOM Exception.

For example, in the following code:

var sound = new Audio();
sound.src = "sound.mp3";
sound.onended = function(event){ console.log('Playing ended.'); }

function play() {
    alert("Sound is playing...");

if you call the play() function everything seems OK, for the first call. But any subsequent call will output "Playing ended" to console twice and throw Uncaught (in promise) DOMException if you keep the alert box open until after the sound finishes playing. What's also puzzling is that Chrome reports exception at the line 1 of the html document!

Why is this happening?

0 Answers