This is because the sound file is loaded asynchronously by JavaScript, and then the code continues to execute. A warning is triggered first because it takes some time to load an audio file.
To fix this, you need to add an event listener at boot, for example:
x.addEventListener('load', function() { x.play(); alert("foo"); });
Or you can add an event listener to the onplay event, for example:
x.onplay = function () { alert("foo"); }; x.play();
source share