How to sleep the thread in node.js without affecting other threads? How to sleep the thread in node.js without affecting other threads? multithreading multithreading

How to sleep the thread in node.js without affecting other threads?


If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

setTimeout(function() {  console.log('hello world!');}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));const example = async () => {  console.log('About to snooze without halting the event loop...');  await snooze(1000);  console.log('done!');};example();


In case you have a loop with an async request in each one and you want a certain time between each request you can use this code:

   var startTimeout = function(timeout, i){        setTimeout(function() {            myAsyncFunc(i).then(function(data){                console.log(data);            })        }, timeout);   }   var myFunc = function(){        timeout = 0;        i = 0;        while(i < 10){            // By calling a function, the i-value is going to be 1.. 10 and not always 10            startTimeout(timeout, i);            // Increase timeout by 1 sec after each call            timeout += 1000;            i++;        }    }

This examples waits 1 second after each request before sending the next one.


Please consider the deasync module, personally I don't like the Promise way to make all functions async, and keyword async/await anythere. And I think the official node.js should consider to expose the event loop API, this will solve the callback hell simply. Node.js is a framework not a language.

var node = require("deasync");node.loop = node.runLoopOnce;var done = 0;// async call heredb.query("select * from ticket", (error, results, fields)=>{    done = 1;});while (!done)    node.loop();// Now, here you go