203

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.

Sebastian Simon
  • 16,564
  • 7
  • 51
  • 69
richardaum
  • 6,362
  • 12
  • 44
  • 59

3 Answers3

194

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() {
   ...
}
Diodeus - James MacFarlane
  • 110,221
  • 32
  • 151
  • 174
  • 4
    Can you pass a parameter to `partB` at `window.setTimeout(partB,1000)`? – brain56 Apr 04 '14 at 08:55
  • 5
    If you wrap it in an anonymous function, such as in Michael Haren's answer, then you can. – Diodeus - James MacFarlane Apr 04 '14 at 14:12
  • 27
    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: http://stackoverflow.com/questions/4122268/using-settimeout-synchronously-in-javascript – cartbeforehorse May 05 '14 at 01:17
  • 2
    This also answers the age-old question of "What comes before Part-B?" – Joeytje50 Dec 18 '14 at 17:03
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.

Davide
  • 1,523
  • 1
  • 14
  • 29
Michael Haren
  • 101,522
  • 39
  • 162
  • 203
  • 9
    `sleep` doesn't block processing; it allows processing to continue. – EML Jun 12 '14 at 19:29
  • Anonymous functions are not recommend as a security risk according to https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout – Wolter Apr 30 '18 at 12:30
  • 3
    @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`. – Michael Haren May 22 '18 at 11:12
13

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

w3schools has an easy tutorial about this function.

raphie
  • 3,239
  • 2
  • 27
  • 26
  • 14
    w3School is not reliable, use this instead: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout – jolySoft Jul 27 '17 at 12:18