How to create a sleep/delay in nodejs that is Bloc

2019-01-12 23:16发布

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?

11条回答
贪生不怕死
2楼-- · 2019-01-12 23:48

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楼-- · 2019-01-12 23:53

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})`);
查看更多
Anthone
4楼-- · 2019-01-12 23:54

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.

查看更多
做个烂人
5楼-- · 2019-01-12 23:56

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!");
});
查看更多
smile是对你的礼貌
6楼-- · 2019-01-12 23:58

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.

查看更多
老娘就宠你
7楼-- · 2019-01-12 23:59

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

查看更多
登录 后发表回答