3
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.

Borut Flis
  • 15,715
  • 30
  • 92
  • 119
  • 1
    Because the prompt blocks all the execution on the page called it. That is said to be a modal window. – Teemu Jan 21 '20 at 11:12

1 Answers1

2

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);
   }

}
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42