What it does:
Speak a random word chosen from an array and ask the user to type the word in the box for 15 seconds
- If right, +1pts, reset the timer and go to next word.
- If wrong: do nothing.
- After 15 seconds: game over.
body {background-color: black; color: white;} .center { width: 50%; height: 50%; position: absolute; top:0; bottom: 0; left: 0; right: 0; margin: auto; } .hidden { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <center class="center start"> <h1> The ListenHear<br>Game<br><br><button class="w3-btn w3-green" onclick="play()">Play</button><button class="w3-btn w3-red" onclick="exit()">Exit</button> </h1> </center> <center class="center hidden"> <h1 id="x"><x class="w3-red">There was an error.</x> </h1> </center> <script> var read; var time = 0; var i = 0; var words; var c; $.getJSON( "https://gist.githubusercontent.com/khanh2003/ae6c144ed12aa4e6dce98c40163935d1/raw/9073f8a40a39ecbe02a38547f99bca9e3637660c/JSON.json", function( data ) { words=data; }); function play() { $(".start").hide(function() { $(".hidden").removeClass("hidden"); $("#x")[0].innerHTML = "<i style='color:green'>Listen and fill in the blank the word(s).</i>"; setTimeout(game,2000); });} function game() { read = words[Math.floor(Math.random()*words.length)]; $("#x")[0].innerHTML = "<input type=text onkeypress=check() style=width:100%></input><button onclick='speechSynthesis.speak(new SpeechSynthesisUtterance(read));'>Again please!</button><br><div class='time'></div><br><button onclick=giveup()>Give up</button>"; $("input").focus(); speechSynthesis.speak(new SpeechSynthesisUtterance(read)); time = 0; c=setInterval(function() { time=time+0.01; $(".time").text(Math.floor(15-time)); if(time>15) {giveup();} }, 10); } function check() { if ($("input")[0].value.toUpperCase() === read.toUpperCase()) { $("#x")[0].innerHTML = "<i style='color:green'>Correct! Score: "+(++i)+"</i>"; time = 0; setTimeout(game,2000); clearInterval(c); } } function giveup() { $("#x")[0].innerHTML = "<i style='color:red'>Time's Up! Score: "+(i)+"<br>The word(s) are: "+read+"</i>"; time=0; setTimeout(play,5000); } function exit() {$("body").slideUp(function() {window.close;});} </script>
For those who are complaining the code is broken, the SpeechSynthesisAPI (the code depends on) doesn’t have good browser support.
Answer
Your game()
calls c=setInterval(…)
, which is balanced by clearInterval(c)
in check()
. However, giveup()
does not call clearInterval(c)
. As a result, if you just start the game but do nothing, then it gets ridiculously faster and faster.
Attribution
Source : Link , Question Author : Community , Answer Author : 200_success