74

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?

7
  • 4
    Sounds to me like you're using the wrong tool for the job. Node was designed to be non blocking, if you want to create a blocking daemon of sorts, you should look into alternative technologies. accuracy of ~10ms in network contexts is easily doable in most languages.... Jan 7, 2014 at 8:36
  • 1
    Or, you could do it the "node" way, use async style to re-model your program logic.
    – Passerby
    Jan 7, 2014 at 8:37
  • 1
    Are you sure you need to block the thread? If you're new to nodejs, then it might just be that you're not used to thinking/designing flow in asynchronous terms yet :) Anyway, there's a sleep package here: npmjs.org/package/sleep (real sleep where supported, busy-wait for windows)
    – Supr
    Jan 7, 2014 at 8:56
  • 1
    That doesn't necessarily imply that it needs to be blocking though, unless setTimeout has too much overhead. I just made a simple test: jsapp.us/#s445.js Running this gives at most 6 ms delay using setTimeout, while blocking is ranging up to 39 ms delay (worst cases are probably due to server being busy with other things, so may not apply in OPs case). But I agree that node.js is probably not suitable if absolute 100% precision and reliability is required.
    – Supr
    Jan 7, 2014 at 11:26
  • 1
    There are legit cases when a blocking solution is needed, for instance, in debugging: to simulate delays while keeping full control over the order of execution. The fact that Node.js doesn't provide a direct solution (although it could) is a deficit of Node, which should not be advertised as a feature, nor used as an excuse for blaming the questioner who asked a sound question. Dec 16, 2021 at 0:59

13 Answers 13

74

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.

17
  • 27
    I think, the right words are "should never be used", because this is a busy waiting.
    – Bakudan
    Jan 7, 2014 at 8:45
  • 8
    @Bakudan - depends, it should never really be used for a webserver, but Node is used for many other things, and in this case the OP is controlling LED's and specifically asks for something to block the thread, and this does that.
    – adeneo
    Jan 7, 2014 at 8:51
  • 8
    Personally, I think that Node.js needs sleep-based blocking. It's wrong to suggest that the author(s) of Node knew all scenarios. What if you need to slow down your activities so that you're not overrunning other people's servers and resources? It's bad netiquette to wear out someone else's, say, email server just because you have a million outbound emails to send and your platform of choice doesn't appear to allow anything to add delays. Thanks, adeneo. May 9, 2015 at 21:53
  • 2
    There are several npm modules available for doing a sleep-based blocking.
    – Timothy Gu
    May 23, 2015 at 1:16
  • 2
    And most of those modules are written after this answer was posted, and using the exact same technique.
    – adeneo
    Jul 31, 2015 at 22:41
43

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")
  });
}
3
  • 2
    This is the most practical way to sleep for applications. However, people should understand that this is not the same as the sleep system call (aka Thread.sleep()) and the contract is that you make the app sleep for at least the given amount, plus the time the callback is queuing in the event queue (typically less than 10 ms). Dec 14, 2021 at 18:09
  • 12
    This function is non-blocking, while the question explicitly asks for a blocking solution. Dec 16, 2021 at 0:28
  • This is FANTASTIC! HRJ, you helped me after frustratingly failing to get this to work. (I'm new to typescript) Jun 2, 2022 at 7:26
42

The best solution is to create singleton controller for your LED which will queue all commands and execute them with specified delay:

function LedController(timeout) {
  this.timeout = timeout || 100;
  this.queue = [];
  this.ready = true;
}

LedController.prototype.send = function(cmd, callback) {
  sendCmdToLed(cmd);
  if (callback) callback();
  // or simply `sendCmdToLed(cmd, callback)` if sendCmdToLed is async
};

LedController.prototype.exec = function() {
  this.queue.push(arguments);
  this.process();
};

LedController.prototype.process = function() {
  if (this.queue.length === 0) return;
  if (!this.ready) return;
  var self = this;
  this.ready = false;
  this.send.apply(this, this.queue.shift());
  setTimeout(function () {
    self.ready = true;
    self.process();
  }, this.timeout);
};

var Led = new LedController();

Now you can call Led.exec and it'll handle all delays for you:

Led.exec(cmd, function() {
  console.log('Command sent');
});
4
  • 12
    I can't believe simple things are so complicated in NodeJS. God bless C# and/or Java!
    – TriCore
    May 1, 2018 at 2:04
  • 2
    @TriCore hopefully, NodeJS support ES6 and async/await now. So timeouts and async operations are no longer that complicated. May 1, 2018 at 11:32
  • 7
    @TriCore God bless Node for making stupid things so complicated, because blocking a single thread is definitely stupid (this doesn't apply to the answer, which is technically wrong because it's non-blocking). @LeonidBeschastny Actually, generators and co existed at the time when the question was asked. Currently async..await is certainly a way to go. Jan 22, 2019 at 23:04
  • ReferenceError: sendCmdToLed is not defined
    – Jortega
    Sep 21, 2020 at 15:54
38

Just use child_process.execSync and call the system's sleep function.

//import child_process module
const child_process = require("child_process");
// Sleep for 5 seconds
child_process.execSync("sleep 5");

// Sleep for 250 microseconds
child_process.execSync("usleep 250");

// Sleep for a variable number of microseconds
var numMicroSeconds = 250;
child_process.execFileSync("usleep", [numMicroSeconds]);

I use this in a loop at the top of my main application script to make Node wait until network drives are attached before running the rest of the application.

2
  • child_process.execSync("sleep 1"); ^ ReferenceError: child_process is not defined
    – sapy
    Aug 16, 2017 at 9:55
  • 3
    @sapy You need to include the child_process module. For example, const child_process = require("child_process");
    – sffc
    Aug 17, 2017 at 22:16
35

use Node sleep package. https://www.npmjs.com/package/sleep.

in your code you can use

var sleep = require('sleep'); 
sleep.sleep(n)

to sleep for a specific n seconds.

2
8

Easiest true sync solution (i.e. no yield/async) I could come up with that works in all OS's without any dependencies is to call the node process to eval an in-line setTimeout expression:

const sleep = (ms) => require("child_process")
    .execSync(`"${process.argv[0]}" -e setTimeout(function(){},${ms})`);
1
  • 3
    This is a nice solution, and using spawnSync() instead avoids escaping issues: spawnSync(process.argv[0], ['-e', 'setTimeout(function(){},' + ms + ')']); and works Windows/Linux
    – bonger
    Jun 27, 2018 at 16:59
5

As the sleep package author suggests *:

function msleep(n) {
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n);
}

function sleep(n) {
  msleep(n * 1000);
}
1
  • Best answer. A great solution (although it Nodejs seems to have meant to not allow sync wait, yet, better than the busy waiting using while since that blocks Node's event queue ).
    – Sohail Si
    May 4, 2022 at 9:08
2

It's pretty trivial to implement with native addon, so someone did that: https://github.com/ErikDubbelboer/node-sleep.git

5
  • 2
    This is mainly useful for debugging purpose or for writing tests. It's a very bad idea to use blocking sleep in production. Jan 7, 2014 at 12:36
  • 2
    sure it is, in most cases. but «production» is a broad term. if you don't need to serve clients, then you can do blocking things. Jan 7, 2014 at 13:17
  • 3
    it is ok if you know what are you doing, js is not just for client-server apps.
    – setec
    Oct 17, 2014 at 9:09
  • If "production" is a bunch of command-line tools for administrators to use (written in node, to use protocol/client code from the main codebase), then lack of synchronous/blocking stuff in node is a total PITA... Async stuff is a "very bad idea in production" in some cases, given the extra testing needed... Nov 20, 2016 at 23:31
  • this should be the accepted solution! the only one that actually block the event loop.
    – Bamieh
    Jul 31, 2017 at 8:08
2

I found something almost working here https://stackoverflow.com/questions/21819858/how-to-wrap-async-function-calls-into-a-sync-function-in-node-js-or-ja vascript

function AnticipatedSyncFunction(){
    var ret;
    setTimeout(function(){
        var startdate = new Date()
        ret = "hello" + startdate;
    },3000);
    while(ret === undefined) {
       require('deasync').runLoopOnce();
    }
    return ret;    
}


var output = AnticipatedSyncFunction();
var startdate = new Date()
console.log(startdate)
console.log("output="+output);`

The unique problem is the date printed isn't correct but the process at least is sequential.

1

Blocking in Node.js is not necessary, even when developing tight hardware solutions. See temporal.js which does not use setTimeout or setIntervalsetImmediate. Instead, it uses setImmediate or nextTick which give much higher resolution task execution, and you can create a linear list of tasks. But you can do it without blocking the thread.

10
  • 6
    Blocking in Node.js is necessary for testing, e.g. when simulating an overloaded server, which does not respond to every request within a timeout. Aug 30, 2016 at 15:50
  • Sometimes it's necessary if other codes are written in returning-style and you don't know how to change all of them to callback-style. Jan 24, 2017 at 8:07
  • @RomulusUrakagiTs'ai "Necessary"? I'd be interested in seeing that example. Can you supply a gist? Jan 24, 2017 at 12:38
  • this.get({'/somepath': function(){ return sendFile('foobar.json').call(this); }); This is a response function, how can you make it wait something without blocking it? Jan 25, 2017 at 2:07
  • @RomulusUrakagiTs'ai What API is that? What do you need to wait for? I'm not following. You mean you need to wait an amount of time? If so, you can use setTimeout() for that... but I'm guessing you are suggesting something else? Jan 25, 2017 at 4:03
1

You can simply use yield feature introduced in ECMA6 and gen-run library:

let run = require('gen-run');


function sleep(time) {
    return function (callback) {
        setTimeout(function(){
            console.log(time);
            callback();
        }, time);
    }
}


run(function*(){
    console.log("befor sleeping!");
    yield sleep(2000);
    console.log("after sleeping!");
});
1

asynchronous call ping command to block current code to execution in specified milliseconds.

  • ping command is Cross-platform
  • start /b means: start program but not show window.

code as below:

const { execSync } = require('child_process')
// delay(blocking) specified milliseconds
function sleep(ms) {
    // special Reserved IPv4 Address(RFC 5736): 192.0.0.0
    // refer: https://en.wikipedia.org/wiki/Reserved_IP_addresses
    execSync(`start /b ping 192.0.0.0 -n 1 -w ${ms} > nul`)
}

// usage
console.log("delay 2500ms start\t:" + (new Date().getTime() / 1000).toFixed(3))
sleep(2500)
console.log("delay 2500ms end\t:" + (new Date().getTime() / 1000).toFixed(3))

notice important: Above is not a precision solution, it just approach the blocking time

-6

blocking the main thread is not a good style for node because in most cases more then one person is using it. You should use settimeout/setinterval in combination with callbacks.

2
  • 2
    I understand it isn't good practice, but in this scenario it's exactly what I need. Node will be controlling a udp server sending commands to a microprocessor controlling light bulb. The micro can only handle a single command at a time, so Node needs to block the thread so other only a single person can control the light at a time.
    – on3al
    Jan 14, 2014 at 5:34
  • 7
    blocking the main thread is not good style for ... is good advice for software that is supposed to run with concurrency, but it's perfect style for the OP's task, regardless of whether it's done in ASM, JS or even PHP. Let's put an end to these mindless "blocking is bad" and "synchronous is satan" cults... Nov 20, 2016 at 23:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.