I'm having some trouble making the program wait for 2 seconds before it continuous. I found a solution using sleep and await, but I get the known syntax error. I tried some solutions here from other threads, but I think I'm doing something wrong. I don't get a syntax error anymore, but it's still not working as it should. Tbh, I really don't know what it does or should be doing..
The goal is to show a random word, speak it, wait 2s, speak it again and replace the word with blank spaces. With this code you do not see the random word, it just speaks it twice (without 2s pause) and only shows the blank spaces. When I remove the await
(and the blank spaces) it works fine.
What am I doing wrong?
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var words = ["meget", "går", "mor", "tog", "sød", "at væare"];
var wordsCorrect = 0;
var wordsWrong = 0;
function textToAudio(random) {
let msg = random;
let speech = new SpeechSynthesisUtterance();
speech.lang = "da-DK";
speech.text = msg;
speech.volume = 1;
speech.rate = 0.5;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
function newWord(words) {
var random = Math.floor(Math.random() * words.length);
document.getElementById("Empty").innerHTML = words[random];
textToAudio(words[random]);
(async() => await sleep(2000))();
textToAudio(words[random]);
words.splice(random, 1);
document.getElementById("Empty").innerHTML = " ";
};
document.getElementById("refresh_word").addEventListener("click", () => newWord(words));
<!DOCTYPE html>
<html>
<head>
<title>Aliyah's dictee spel</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="header">
<h1>Hej! Velkommen til Aliyahs diktee!</h1>
</div>
<div id="Random_word">
<h2 id="Empty">Click new word to start</h2>
<button id="refresh_word">new word</button>
</div>
<input type="text" id="input1" />
<input type="submit" name="ok" value="ok" />
<script>
</script>
</body>
</html>