I tried to work this code:
var foo=0
window.onmouseup=function(){
foo=1
}
window.onmousedown=function(){
while(foo==0);
console.log("bar")
}
the "bar" is not shown and the browser (I use Edge) stuck there(unable to close the page), I had to use Ctrl+T and then Ctrl+W
I guess the problem is foo==0 is optimized, so it reads from the cache, but I don't know how to avoid it. Or are there other methods?
You could use setInterval() and put the if statement and the rest of the code in there:
var foo = 0
window.onmouseup = function() {
foo = 1
}
window.onmousedown = function() {
var interval = setInterval(() => {
if (foo !== 0) {
clearInterval(interval);
console.log("bar")
}
});
}
Actually, I think the problem is that your while loop will just continue running until it "breaks", or ends the loop. However, foo will always be 1 and never 0 after mouseup, therefore the program gets stuck in the while loop forever, and no other tasks on the browser including the important ones get run.
TL:DR program stuck on while