栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在阻塞的nodejs中创建睡眠/延迟?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在阻塞的nodejs中创建睡眠/延迟?

最好的解决方案是为您的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');});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/375442.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号