最好的解决方案是为您的LED创建单例控制器,该控制器将排队所有命令并以指定的延迟执行它们:
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();现在您可以拨打电话
Led.exec,它将为您处理所有延迟:
Led.exec(cmd, function() { console.log('Command sent');});


