I have a 2 JS files in my program, and one is calling a function in another file, and passing two arguments to it. No issues there - the loop on the 2nd file works as expected - until it gets to terminating. I'm doing something similar in another part of my app with no issues at all.
Code from file 1 (this loop is called from an event on the page - it returns a function so I can include the arguments without calling the function):
let loopStat = false;
let j = 0;
const sleep = (milliseconds) => {
return new Promise(resolve => setInterval(resolve, milliseconds))
}
const callLoop = (item) => {
return function() {
loopStat = !loopStat;
loopFunc(loopStat, item);
}
}
const loopFunc = async (z, item) => {
console.log('before loop', z);
while (z == true) {
console.log('inside loop', z);
j++;
console.log(j);
await sleep(1000);
}
}
var button = document.getElementById('button')
button.addEventListener("click", callLoop(button));
<div id="parent">
<button id="button">Loop</button>
</div>
Obviously "z" is used to terminate the loop in this function. I included the "console.log" bits to show what "z" is at different points. When the button is clicked again, it toggles the "loopStat" variable to false, calls the function again and sends that argument along. The weird thing is, the new argument is being sent to the function(as shown in the 'before loop' console.log), but inside the loop it changes "z" back to true, as shown in the 'inside loop' console.log.
I think it's also worth mentioning that the variables "z" and "loopStat" are not used anywhere else in the app.
I'm expecting the solution to be something obvious, and I'm suspecting it's a scope issue.
zis nottrueat the start of the while loop in loopFunc, the while-loop won't execute. Ok. But ifzistrue, nothing in the loop changes the value ofz, so it will never become false and the loop will never terminate. (and … you never need(something == true)-- that can always be rewritten as(something)e.g.if (outcome == true)becomesif (outcome))zis a local variable that contains the original value ofloopStatwhen it was called. ChangingloopStatin an event handler will not change the value ofz.setIntervalbesetTimeoutinstead?setIntervaldoesn't make a lot of sense for how it has been implemented.