[英]How to safely send message to a running function in javascript
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 “栏”未显示,浏览器(我使用 Edge)卡在那里(无法关闭页面),我不得不使用 Ctrl+T,然后使用 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.我猜问题是
foo==0
被优化了,所以它从缓存中读取,但我不知道如何避免它。 Or are there other methods?或者还有其他方法吗?
You could use setInterval()
and put the if statement and the rest of the code in there:您可以使用
setInterval()
并将 if 语句和代码的 rest 放在那里:
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.实际上,我认为问题在于您的 while 循环将继续运行直到它“中断”或结束循环。 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.但是,在
mouseup
之后foo
将始终为1
而永远不会0
,因此程序将永远卡在 while 循环中,并且浏览器上的其他任务(包括重要任务)都不会运行。
TL:DR program stuck on while
TL:DR 程序卡住
while
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.