为什么javascript中setTimeout没有执行
我有一个在 javascript 中休眠的函数,如下所示:
var is_sleep = true;
function sleep(time){
if (is_sleep){
is_sleep = false;
setTimeout("sleep(time)", time);
}else{
is_sleep = true;
}
}
sleep(3000);
但是它运行 is_sleep=true 的语句,不运行 is_sleep=false 语句并且不再休眠。
有人能说出原因是什么吗?先感谢您。
I have a function to sleep in javascript like below:
var is_sleep = true;
function sleep(time){
if (is_sleep){
is_sleep = false;
setTimeout("sleep(time)", time);
}else{
is_sleep = true;
}
}
sleep(3000);
However it runs through the statements for is_sleep=true, doesn't run through is_sleep=false statements and doesn't sleep any more.
Could someone tell what the reason is? Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可能正在调用
setTimeout
,但传递给它的字符串失败,因为作用域将不再包含您正在引用的time
。尝试用以下内容替换该行:...它定义了一个闭包,它使用正确的范围。您也可以尝试以下操作:
...它将把
time
作为参数传递给sleep
。It's likely that
setTimeout
is being called, but the string passed to it is failing, as the scope will no longer containtime
, which you're referencing. Try replacing that line with this:...which defines a closure, which uses the correct scope. You could also try this:
...which will pass
time
as an argument tosleep
.setTimeout
运行 异步 意味着它不会阻止您的代码执行。也许您知道这一点,但该函数永远不会辜负您为其选择的名称。首先调用
sleep(3000);
调用sleep函数,使is_sleep
变量false
,设置一个定时器,然后立即返回代码执行(sleep(3000);
;))如果
setTimeout
被正确调用 (setTimeout(sleep,time,time);
), 3 秒后,该函数将再次被调用,并将is_sleep
设置回true
。setTimeout
runs asynchronously meaning it's not blocking your code execution. Perhaps you knew that, but the function will never live up to the name you chose for it.First call
sleep(3000);
calls the sleep function, making theis_sleep
variablefalse
, setting a timer, and then immediately returns code execution (to whatever comes aftersleep(3000);
;))If
setTimeout
was called properly (setTimeout(sleep,time,time);
), after 3 seconds, the function would again be called settingis_sleep
back totrue
.