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?
Just use
child_process.execSync
and call the system's sleep function.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.
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
to be used as
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.
Blocking in Node.js is not necessary, even when developing tight hardware solutions. See temporal.js which does not use
setTimeout
orsetInterval
setImmediate. Instead, it usessetImmediate
ornextTick
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.The best solution is to create singleton controller for your LED which will queue all commands and execute them with specified delay:
Now you can call
Led.exec
and it'll handle all delays for you: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
The unique problem is the date printed isn't correct but the process at least is sequential.