如何在阻塞的nodejs中创建睡眠/延迟? [英] How to create a sleep/delay in nodejs that is Blocking?

查看:1373
本文介绍了如何在阻塞的nodejs中创建睡眠/延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试学习nodejs和我正在编写的一个小项目正在编写一个API来控制一些联网的LED灯。

I'm currently trying to learn nodejs and a small project I'm working is writing an API to control some networked LED lights.

控制LED的微处理器有一个处理延迟,我需要空间命令发送到微距离至少100毫秒。在C#中,我习惯只调用Thread.Sleep(时间),但我没有在节点中找到类似的功能。

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.

我找到了几个使用setTimeout的解决方案(...)函数在节点中,但是,这是异步的并且不会阻塞线程(这是我在这种情况下需要的)。

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).

是否有人知道阻塞睡眠或延迟功能?最好不要只旋转CPU,精度为+ -10 ms?

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?

推荐答案

最好的解决办法是为你的LED创建单独控制器,它将排队所有命令并以指定的延迟执行它们:

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();

现在你可以拨打 Led.exec 并且它将为您处理所有延迟:

Now you can call Led.exec and it'll handle all delays for you:

Led.exec(cmd, function() {
  console.log('Command sent');
});

这篇关于如何在阻塞的nodejs中创建睡眠/延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆