How to use SpeechSynthesis inside a setInterval function?

168 Views Asked by At

I need a way to continuously use speech synthesis (like a word every 5 seconds) after the user has done an action like pressing a button.

But I can't create this behavior using setInterval on Safari browsers. This is my code, removing the setInterval function works fine. But enabling setInterval to work every 5 seconds fails.

Code in codepen.io

<button type="button" id="speakBtn" disabled>Speak</button>
if ('speechSynthesis' in window) {
  speechSynthesis.cancel();
  speechSynthesis.getVoices();
  speakBtn.disabled = false;
}

const speak = () => {
  // Works without setInterval:
  setInterval(function () {
    const utter = new SpeechSynthesisUtterance();
    utter.text = "Hello world";
    speechSynthesis.speak(utter);
  }, 5000);
};

speakBtn.addEventListener('click', speak);
0

There are 0 best solutions below