I’m still a bit new to web development, and I’m working on a project using HTML and JavaScript. Here is the problem I’m encountering.
<body>
<h1>random heading</h1>
<button id="clickme">clickme</button>
<p id="yes"></p>
<p id="no"></p>
<script>
const clickme = document.querySelector('#clickme')
const yes = document.querySelector('#yes')
const no = document.querySelector('#no')
let yesScore = 0;
let noScore = 0;
function game() {
clickme.addEventListener('click', myFunction);
function myFunction(){
let promptVar = prompt('y/n');
if(promptVar === 'y') yes.textContent = ++yesScore;
else if(promptVar === 'n') no.textContent = ++noScore;
else return;
if(yesScore + noScore === 5){
console.log('over');
}
}
}
</script>
</body>
So my problem here is that I would like for the game() function to be exited when (yesScore + noScore === 5), but if I use return or break in the if statement, it only exits the myFunction() function.
I’ve tried using a label to jump out of the function directly after the console.log(‘over’) to the outside of the game() function, only to learn that a label can’t jump across function boundaries.
2
Answers
I think you should compare like
yesScore + noScore >= 5
before increase the variables.This is
myfunction
declaration code.You could do like pause inside of game function after myFunction.
That will pause that thread and nothing after it may run after it.
Also, I suggest having myFunction before addEventListener.
=== is exact equals, I suggest using ==. You could also have an end function instead of ending in game(). You may remove an event listener inside an event listener. Like someView.removeEventListener(this);. I find trying to end by being inside game() to be hard and with better alternatives. game() has all functions return imediately so if you want to end with game(), try like initial like game(initial=true) then setTimeout or setInterval with a time and a function calling game with initial = false like game(false) and if initial, set event listener, check for end condition, then if not end condition, setTimeout, or continue with intervals, but if end condition no new timeout, clearInterval with function passed to it, one or other. With if end condition, then do what you would to end. setTimeout and setInterval allow code after them to run before end. Like this:
X E.