SpeechSynthesis onend bug workaround

by pilyugin

JavaScript

var wordsToSpeak = [
  'Hello! This text should be longer than sixty or may be more symbols. Please see console log.',
  'Now end event is fired!',
  'You can use global variables to store utterance object.'
];
// this object for storing utterances globally
window.utterances = [];

function speak(text) {
  var utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = 'en-US';
  utterance.onend = function() {
    // this code is not called
    console.log(text);
  };

  // if you will comment this line, end event will not work!
  utterances.push(utterance);
  
  speechSynthesis.speak(utterance);
}

for (var i = 0; i < wordsToSpeak.length; i++) {
  speak(wordsToSpeak[i])
}