What is the JavaScript version of sleep()?

Is there a better way to engineer a sleep in JavaScript than the following pausecomp 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 - delay between actions; I want a real sleep in the middle of a function, and not a delay before a piece of code executes.

Text Copied From stackoverflow.com
on : Thu, Jun 04, 2009 Views : 1673361

Accepted Answer

2017 update

Since 2009 when this question was asked, JavaScript has evolved significantly. All other answers are now obsolete or overly complicated. Here is the current best 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 second later');
 
}  demo();
 

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

You can try this code live on Runkit. Note that,

  1. await can only be executed in functions prefixed with the async keyword. Runkit wraps your code in an async function before executing it.
  2. await only pauses the current async function

Two new JavaScript features helped write this actual sleep function:

Compatibility

If for some reason you're using Node older than 7, 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. Run

npm install babel-cli --save 

Create .babelrc with:



{
   plugins: [
  transform-async-to-generator,   ] 

Then run your code with

node_modules/babel-cli/bin/babel-node.js sleep.js 

But again, you don't need this if you're using Node 7 or later, or if you're targeting modern browsers.

Text Copied From stackoverflow.com
on : Fri, Oct 07, 2016

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp