为什么javascript中setTimeout没有执行

发布于 2024-10-19 04:06:21 字数 317 浏览 4 评论 0原文

我有一个在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风启觞 2024-10-26 04:06:21

可能正在调用 setTimeout,但传递给它的字符串失败,因为作用域将不再包含您正在引用的 time。尝试用以下内容替换该行:

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

...它定义了一个闭包,它使用正确的范围。您也可以尝试以下操作:

setTimeout(sleep, time, 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 contain time, which you're referencing. 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.

躲猫猫 2024-10-26 04:06:21

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 the is_sleep variable false, setting a timer, and then immediately returns code execution (to whatever comes after 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文