我目前正在尝试学习nodejs,而我正在做的一个小项目正在编写一个API,以控制一些联网的LED灯。
控制LED的微处理器具有处理延迟,我需要将发送给微控制器的命令间隔至少100毫秒。在C#中,我习惯于仅调用Thread.Sleep(time),但在node中没有找到类似的功能。
我已经找到了在节点中使用setTimeout(...)函数的几种解决方案,但是,这是异步的并且不会阻塞线程(这是我在此方案中需要的)。
有人知道阻塞睡眠或延迟功能吗?最好是一些不仅仅使CPU旋转并且具有+ -10毫秒精度的东西?
最好的解决方案是为您的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');
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句