Is there a Sleep/Pause/Wait function in JavaScript?

JavascriptSleep

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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() {
   ...
}

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

w3schools has an easy tutorial about this function.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrichardaumView Question on Stackoverflow
Solution 1 - JavascriptDiodeus - James MacFarlaneView Answer on Stackoverflow
Solution 2 - JavascriptMichael HarenView Answer on Stackoverflow
Solution 3 - JavascriptraphieView Answer on Stackoverflow