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

后端 未结 12 636
爱一瞬间的悲伤
爱一瞬间的悲伤 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:21

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 07:22

    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")
      });
    }
    
    0 讨论(0)
  • 2020-12-02 07:23

    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.

    0 讨论(0)
  • 2020-12-02 07:23

    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!");
    });
    
    0 讨论(0)
  • 2020-12-02 07:25

    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})`);
    
    0 讨论(0)
提交回复
热议问题