简体   繁体   English

为什么setTimeout没有在javascript中执行

[英]why setTimeout is not executed in javascript

I have a function to sleep in javascript like below: 我有一个可以在javascript中进行睡眠的功能,如下所示:

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. 但是,它通过is_sleep = true语句运行,不通过is_sleep = false语句运行,并且不再休眠。

Could someone tell what the reason is? 有人可以说出原因吗? Thank you in advance. 先感谢您。

It's likely that setTimeout is being called, but the string passed to it is failing, as the scope will no longer contain time , which you're referencing. 可能正在调用setTimeout ,但是传递给它的字符串失败了,因为作用域将不再包含time ,您正在引用它。 Try replacing that line with this: 尝试用以下命令替换该行:

setTimeout(function() { sleep(time); }, time);

...which defines a closure, which uses the correct scope. ...定义了一个使用正确范围的闭包。 You could also try this: 您也可以尝试以下方法:

setTimeout(sleep, time, time);

...which will pass time as an argument to sleep . ...这将time作为sleep的理由。

setTimeout runs asynchronously meaning it's not blocking your code execution. setTimeout 异步运行,这意味着它不会阻止代码执行。 Perhaps you knew that, but the function will never live up to the name you chose for it. 也许您知道这一点,但是该功能永远不会辜负您为其选择的名称。

First call sleep(3000); sleep(3000); calls the sleep function, making the is_sleep variable false , setting a timer, and then immediately returns code execution (to whatever comes after sleep(3000); ;)) 调用sleep函数,将is_sleep变量设置为false ,设置一个计时器,然后立即返回代码执行(对sleep(3000);之后的所有内容;))

If setTimeout was called properly ( setTimeout(sleep,time,time); ), after 3 seconds, the function would again be called setting is_sleep back to true . 如果正确调用了setTimeoutsetTimeout(sleep,time,time); ),则在3秒钟后,将再次调用该函数,将is_sleep设置为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM