204

Is there a JavaScript function that simulates the operation of the sleep function in PHP — a function that pauses code execution for x milliseconds, and then resumes where it left off?

I found some things here on Stack Overflow, but nothing useful.

0

3 Answers 3

192

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you pass a parameter to partB at window.setTimeout(partB,1000)?
If you wrap it in an anonymous function, such as in Michael Haren's answer, then you can.
This answer is only half correct. setTimeout() is not the same as sleep(). setTimeout() schedules the named function to be executed asynchronously at a set time in the future. The rest of your code will not wait until the partB function has executed, which is not the same functionality as sleep(). See: stackoverflow.com/questions/4122268/…
This also answers the age-old question of "What comes before Part-B?"
122

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

3 Comments

sleep doesn't block processing; it allows processing to continue.
Anonymous functions are not recommend as a security risk according to developer.mozilla.org/en-US/docs/Web/API/…
@Bananenaffe- if I'm reading the right warning on that docs page, the concern isn't around anonymous functions, it's with code passed as a string, which must be executed via eval.
13

setTimeout() function it's use to delay a process in JavaScript.

w3schools has an easy tutorial about this function.

1 Comment

w3School is not reliable, use this instead: developer.mozilla.org/en-US/docs/Web/API/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.