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

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

    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');
    });
    

提交回复
热议问题