0

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you very much. Could you tell me why time in "sleep(time)" is not the time scope? i don't understand it even though it worked, :-)
@ywenbo: Sure. When you pass a string as a parameter to setTimeout, when the timeout goes off, it will eval it in window's scope. time won't be in window's scope; it will be in sleep's now-inaccessible scope. If you use a closure, it inherits the scope from where it's defined. If you use the second method, then it passes sleep as a reference and tells setTimeout to pass time as an argument to it.
very strong and clear explanation, you're nice and great, i very appreciate your help.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.