Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
loretoparisi Avatar asked Oct 25 '17 16:10

loretoparisi


Video Answer


2 Answers

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");
like image 57
Jonas Wilms Avatar answered Oct 16 '22 06:10

Jonas Wilms


function sleep(time, func){
    if (typeof func === 'function'){
        const timer = ms => new Promise( res => setTimeout(res, ms));
        timer(time).then(i=>func());
    }
    else{
        console.log('What about the function bro?')
    }
}
sleep(1000, function(){
    console.log('hello')
    console.log('test')
    var arr = [1,2,3,4]
    arr.forEach(i => console.log(i))
})
like image 41
Myxi Avatar answered Oct 16 '22 08:10

Myxi