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

后端 未结 12 673
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 07:00

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 LED

12条回答
  •  感情败类
    2020-12-02 07:22

    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.

提交回复
热议问题