开发者

why setTimeout is not executed in javascript

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 rea开发者_JS百科son 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. 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜