[英]html5 and javascript: is setTimeout breaking this?
I am confused as to why the following html is not working. 我对为什么以下html无法正常工作感到困惑。 I would expect it to keep sending alerts but it stops after one.
我希望它会继续发送警报,但是在发出警报后会停止。 Furthermore, the "left fn" alert never occurs!
而且,“ left fn”警报永远不会发生! Can anyone explain this to me?
有人可以向我解释吗? I am using html5 with javascript in firefox on ubuntu.
我在ubuntu上的Firefox中使用html5和javascript。
<!DOCTYPE html>
<script>
function alertme() {
alert ("in fn");
}
while (true) {
window.setTimeout(alertme(), 3000);
alert("left fn");
}
</script>
while (true) {
window.setTimeout(alertme, 3000); //setTimeout wants a function, not the return value of the function
alert("left fn");
}
btw, have fun with klicking all the messageboxes away... 顺便说一句,快点踢掉所有的消息框...
A few probable issues: 一些可能的问题:
alertme()
is being called immediately and its return
value is instead being passed to setTimeout()
. alertme()
被立即调用,并且其return
值被传递给setTimeout()
。
To fix this, you can pass alertme
as a reference (without the calling parenthesis): 要解决此问题,您可以将
alertme
作为参考传递(不带调用括号):
setTimeout(alertme, 3000);
However, this will then conflict with JavaScript's (primarily) single-threaded nature. 但是,这将与JavaScript的(主要)单线程性质发生冲突。
The setTimeout()
s, being asynchronous, simply start a timer that expires no less than 3 seconds from now. setTimeout()
是异步的,只需启动一个计时器,此计时器从现在起持续不少于 3秒钟。 But, they require that the one thread is eventually not busy for the delayed task to be performed. 但是,他们要求一个线程最终不忙于执行延迟的任务。
However, the while (true) {}
, being synchronous and indefinite, will keep the thread busy until all execution is stopped and will never allow the timeouts to perform their tasks. 但是,
while (true) {}
是同步且不确定的,它将使线程保持忙碌状态,直到所有执行停止为止,并且永远不会允许超时执行其任务。 So, you will never see "in fn"
. 因此,您将永远不会看到
"in fn"
。
John Resig has a good write up on timers: http://ejohn.org/blog/how-javascript-timers-work/ John Resig在计时器方面写得很好: http : //ejohn.org/blog/how-javascript-timers-work/
How exactly to fix the code depends on the intent. 如何精确地修复代码取决于意图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.