Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sleep/delay in nodejs that is Blocking?

I'm currently trying to learn nodejs and a small project I'm working is writing an API to control some networked LED lights.

The microprocessor controlling the LEDs has a processing delay, and I need to space commands sent to the micro at least 100ms apart. In C# I'm used to just calling Thread.Sleep(time), but I have not found a similar feature in node.

I have found several solutions using the setTimeout(...) function in node, however, this is asynchronous and does not block the thread ( which is what I need in this scenario).

Is anyone aware of a blocking sleep or delay function? Preferably something that does not just spin the CPU, and has an accuracy of +-10 ms?

like image 622
on3al Avatar asked Jan 07 '14 08:01

on3al


People also ask

Does setTimeout block NodeJS?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.

How do you sleep 3 seconds in JavaScript?

Initially the text in the async function "Hello Tutorix" is displayed once the function is started. Later on, the function is paused using sleep function for 3 seconds. Once the time period is completed, the text("Welcome to ........") following the sleep function is displayed.


2 Answers

Node is asynchronous by nature, and that's what's great about it, so you really shouldn't be blocking the thread, but as this seems to be for a project controlling LED's, I'll post a workaraound anyway, even if it's not a very good one and shouldn't be used (seriously).

A while loop will block the thread, so you can create your own sleep function

function sleep(time, callback) {     var stop = new Date().getTime();     while(new Date().getTime() < stop + time) {         ;     }     callback(); } 

to be used as

sleep(1000, function() {    // executes after one second, and blocks the thread }); 

I think this is the only way to block the thread (in principle), keeping it busy in a loop, as Node doesn't have any blocking functionality built in, as it would sorta defeat the purpose of the async behaviour.

like image 84
adeneo Avatar answered Sep 21 '22 16:09

adeneo


With ECMA script 2017 (supported by Node 7.6 and above), it becomes a one-liner:

function sleep(millis) {   return new Promise(resolve => setTimeout(resolve, millis)); }  // Usage in async function async function test() {   await sleep(1000)   console.log("one second has elapsed") }  // Usage in normal function function test2() {   sleep(1000).then(() => {     console.log("one second has elapsed")   }); } 
like image 21
HRJ Avatar answered Sep 19 '22 16:09

HRJ