Search code examples
javascriptnode.jsmultithreadingsleep

Sleep in Node.js


Assumed that there is no "native" way to achieve this, my solution-like was

sleep = function(time) {
        var stop = new Date().getTime();
        while(new Date().getTime() < stop + time) {
            ;
        }
        return new Promise((r,_)=> r())
      }

So doing sleep(1000*3).then(()=>console.log("awake")) it will sleep 3 seconds and then resolve the Promise:

(be aware that it will freeze this page one sec.)

sleep = function(time) {
  var stop = new Date().getTime();
  while (new Date().getTime() < stop + time) {;
  }
  return new Promise((r, _) => r())
}
console.log("sleeping...")
sleep(1000 * 1).then(() => console.log("awake"))

Assumed that this will run in the main thread it will freeze the main process so that doing

sleep(1000*1).then(()=>console.log("awake")); console.log("Hello")

it will result in a output

VM2628:1 Hello
VM2628:1 awake

at very end of the sleep. Of course doing

setTimeout(()=>sleep(1000*3).then(()=>console.log("awake")),1000);console.log("Hello")
VM2815:1 Hello
undefined
VM2815:1 awake

will make it async, but it does not address my need (to put to sleep my main process). Any better way?

[UPDATE] Promisified version

/**
 * Sleep for time [msec]
 * @param time int milliseconds
 * @return Promise delayed resolve
 * @usage
    sleep(1000*3).then(()=>console.log("awake"))
 */
sleepP: function (time) {
  return new Promise((resolve, reject) => {
    var stop = new Date().getTime();
    while (new Date().getTime() < stop + time) {
      ;
    }
    return resolve(true)
  });
}

that can be called like

await sleepP( 1000 * 3 );

Solution

  • There is no need to freeze at all. Because of javascripts asynchronicity we can leave a part of the code for some time and resume later. At first we need a promising timer:

     const timer = ms => new Promise( res => setTimeout(res, ms));
    

    Then we can simply use it:

    console.log("wait 3 seconds")
    timer(3000).then(_=>console.log("done"));
    

    Or with a bit syntactic sugar:

    (async function(){
      console.log("wait 3 seconds");
      await timer(3000);
      console.log("done");
    })()
    

    If you really want to freeze ( very bad ), you don't need promises at all:

    function freeze(time) {
        const stop = new Date().getTime() + time;
        while(new Date().getTime() < stop);       
    }
    
    console.log("freeze 3s");
    freeze(3000);
    console.log("done");