What is the JavaScript version of sleep()?

Solution:

2017 — 2021 update

JavaScript has significantly evolved since 2009, the year this question was originally asked. All other answers are either obsolete or excessively complex. This is the best current practice:

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

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two seconds later, showing sleep in a loop...');

  // Sleep in loop
  for (let i = 0; i < 5; i++) {
    if (i === 3)
      await sleep(2000);
    console.log(i);
  }
}

demo();

This is it. await sleep(<duration>).

Or you can write a brief summary:

await new Promise(r => setTimeout(r, 2000));

Be aware that

  1. Waiting can only occur in functions that have been prefixed with the async keyword, or at a higher level in your script for a growing number of environments.
  2. The await  function only pauses the async  function at the moment. It is not blocking the execution the rest of your script. This is what you want in almost all cases. If you want to use  Atomics, this is the answer. You will need to wait, However, most browsers won’t allow it in the main thread.

Two new JavaScript JavaScript capabilities (as of 2017), helped to write this “sleep” functionality:

  • Promises is a native feature (aka ES6) of ES2015. We also use the arrow function in the definitions of the sleep function.
  • The async/await functionality allows the code to wait indefinitely for a promise of settlement (resolve or decline).

Compatibility

  • Node v0.12+ promises are supported and widely supported by browsers.
  • Async/await has been introduced in V8 and is enabled by default from Chrome 55 (released December 2016).
    • It landed in Node 7 October 2016
    • And also appeared in Firefox Nightly on November 16, 2016.

If, for some weird reason, you’re using Node older than 7 (which has reached the end of life), or are targeting old browsers, async/await can still be used via Babel (a tool that will transpile JavaScript + new features into plain old JavaScript), with the transform-async-to-generator plugin.

(Refer to the updated 2016 answer.

I believe it is reasonable to want an action to be performed, followed by a wait to complete another one. If you’re used to writing in multithreaded languages, then you may have the idea that execution should be stopped for a time before your thread wakes.

JavaScript, which is a single-thread event-based system, is the problem. While it may be beneficial in certain situations to have the whole engine wait a few seconds, it is generally bad practice. Imagine I wanted your functions to be used while writing my own. I would experience a complete freeze in my methods when I called your service. JavaScript could keep your function’s execution environment, store it somewhere and bring it back later. This would allow for sleep, but it would essentially be threading.

You’re stuck with what others have said — you’ll need break down your code into multiple functionalities.

Your question is misleading. There is no way to get your sleep exactly the way that you desire, and there should be no reason to pursue the solution you propose.

JavaScript is a language that allows you to rewrite functions so they can end as soon and efficiently as possible. You want your browser back in control, so it can make DOM modifications.

I have refactored every time I want to sleep in the middle a function.

Edit

It is a controversial topic to discuss the sleep function or delay in any language. Some will argue there should be a signal or callback that fires a specific functionality. Others will argue it is sometimes useful to have an arbitrary delay. I say, “To each his own” in this industry.

JavaScript promises makes it easy to write sleep functions.

// sleep time expects milliseconds
function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

// Usage!
sleep(500).then(() => {
    // Do something after the sleep!
});

 

 

How To Use Data Analytics To Improve Email Marketing Campaigns Top 8 Dominating Mobile App Trends in 2022 How to make a car safe for long journeys? Everything You Expect to Learn About VPN for Windows Top 7 Benefits of B2B Marketing Strategy Characteristics Held in common with All Customer-Friendly LMS Solutions