What is the JavaScript version of sleep()? -


is there better way engineer sleep in javascript following pausecomp function (taken here)?

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

this not duplicate of sleep in javascript - delay between actions; want real sleep in middle of function, , not delay before piece of code executes.

2017 update

since 2009 when question asked, javascript has evolved significantly. other answers obsolete or overly complicated. here current best practice:

function sleep(ms) {   return new promise(resolve => settimeout(resolve, ms)); }  async function demo() {   console.log('taking break...');   await sleep(2000);   console.log('two second later'); }  demo(); 

this it. await sleep(<duration>).

you can try code live on runkit. note that,

  1. await can executed in functions prefixed async keyword. runkit wraps code in async function before executing it.
  2. await pauses current async function

two new javascript features helped write actual "sleep" function:

compatibility

if reason you're using node older 7, or targeting old browsers, async/await can still used via babel (a tool transpile javascript + new features plain old javascript), transform-async-to-generator plugin. run

npm install babel-cli --save 

create .babelrc with:

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

then run code with

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

but again, don't need if you're using node 7 or later, or if you're targeting modern browsers.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -