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,
await
can executed in functions prefixedasync
keyword. runkit wraps code in async function before executing it.await
pauses currentasync
function
two new javascript features helped write actual "sleep" function:
- promises, native feature of es2015 (aka es6). use arrow functions in definition of sleep function.
- the upcoming
async/await
feature lets code explicitly wait promise settle.
compatibility
- promises supported in node v0.12+ , widely supported in browsers, except ie
async
/await
landed in v8 , has been enabled default since chrome 55
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
Post a Comment