fmsf fmsf - 1 year ago 110
Javascript Question

What is the JavaScript version of sleep()?

Is there a better way to engineer a

in JavaScript than the following
function (taken from here)?

function pausecomp(millis)
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis);

This is not a duplicate of Sleep in Javascript; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

Answer Source

In JavaScript, I rewrite every function so that it can end as soon as possible. You want the browser back in control so it can make your DOM changes.

Every time I've wanted a sleep in the middle of my function, I refactored to use a setTimeout().

I am going to edit this answer because i found this as useful:

The infamous sleep, or delay, function within any language is much debated. Some will say that there should always be a signal or callback to fire a given functionality, others will argue that sometimes an arbitrary moment of delay is useful. I say that to each their own and one rule can never dictate anything in this industry.

Writing a sleep function is simple and made even more usable with JavaScript Promises:

function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));

// Usage!
sleep(500).then(() => {
    // Do something after the sleep!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download