Search code examples
javascriptasynchronousaudiopromptsingle-threaded

Why is the audio executed after the prompt?


function myTimer() {
    randint= Math.floor(Math.random() * 10)+1;
    randstimuli=gorilla.stimuliURL(dict[randint]);
    var audio = new Audio(randstimuli);
    audio.play();
    var start=Date.now();
    var ans=prompt("was the last number the same as the one two steps ago");
    console.log(Date.now()-start);
}

I have this function in which I play a sound and ask the user via the prompt a question. When I run the function sound is played immediately after answering the prompt, even though the audio precedes the prompt in the code. Due to the single-threaded nature of Javascript I assume the audio is run asynchronously, due to an assumption of the audio length.

My audio are very short, they contain just one word. I want them to be finished before the prompt opens.


Solution

  • You could listen to the onended event of the audio and perform the action in the callback.

    Example:

    
    function myTimer() {
       randint = Math.floor(Math.random() * 10) + 1;
       randstimuli = gorilla.stimuliURL(dict[randint]);
       var audio = new Audio(randstimuli);
       audio.play();
       audio.onended = function () {
          var start = Date.now();
          var ans = prompt("was the last number the same as the one two steps ago");
          console.log(Date.now() - start);
       }
    
    }