I encountered a problem in my code, here it is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function typeWriter() {
function genOutput() {
function genText() {
//generate random alphabet via ASCII char code
return String.fromCharCode(0|Math.random()*26+97);
}
const text = document.getElementById("genText");
text.textContent = genText() + text.textContent;
}
const text = document.getElementById("genText");
const score = document.getElementById("scoreBoard");
text.textContent = "";
window.setInterval(genOutput, 400); //automatically generate one charracter per 0.4 sec
document.addEventListener('keypress', (e) => {
const input = String.fromCharCode(e.charCode);
const lastCharacter = text.textContent.charAt(text.textContent.length-1);
if (input == lastCharacter) {
const newText = text.textContent.slice(0, -1);
text.textContent = newText;
score.innerText = "" + (parseInt(score.innerText)+3);
}
else if (input == " ") {
//check if user type space bar
alert("Click to continue"); //if remove this alert will occur exception
}
else {
score.innerText = "" + (parseInt(score.innerText)-1);
}
})
}
</script>
<div class="container">
<p id="title">Typewriter 2.0</p>
</div>
<div class="container">
<h1 id="genText">Typed correct +3 pt, incorrect -1 pt</h1><br>
<button id="startBtn" onclick="typeWriter()">Click to Start</button>
<span>Score: </span><span id="scoreBoard">10</span>
</div>
</body>
</html>
The provided code showcases a typewriter web game that randomly generates an alphabet every 400ms and removes the last character if typed correctly. However, there is an issue when the user types the space bar as it restarts the countdown interval and generates multiple alphabets at once. To prevent this exception, an alert function was added upon typing the space bar which acts as a pause button. Can anyone provide insights on why this exception occurs? Your help is highly appreciated!