gpt4 book ai didi

javascript - setInterval导致内存溢出?

转载 作者:行者123 更新时间:2023-12-03 09:29:25 25 4
gpt4 key购买 nike

郑重声明,我的大部分编程都使用 Node API。不管怎样,当我运行我的代码时,我收到内存泄漏错误,说有 11 个发射器打开。如果是这种情况,我将如何防止我的程序打开多个 getData 实例?如果我无法阻止这种情况,是否有一种粗略的方法来删除我不希望发出的实例?我试图每 50 毫秒运行一次该函数。这是我的代码:

setInterval(getData, 100);

function getData() {
"use strict";
//When the serialport opens:
serialport.on("open", function() {
serialport.on("data", function(data) {
//Takes the current string value, turns it into an integer, then stores it in nCurrentValue
runData( parseInt(data.toString()) );
});
});
}
getData();

function runData(value) {
"use strict";
socket.emit('NewData',value);
console.log(value);
}

最佳答案

您可以通过在 getData 之外提取事件触发器来完成此操作。据我了解,nodejs 是事件驱动的,因此您应该只附加 onopen/ondata 一次,然后所有连接都将通过您的函数调用进行。

我想你只需要执行以下操作:

serialport.on("open", newConnection);
serialport.on("data", newDataReceived);

function newConnection() {
// do something with the connection...
}

function newDataReceived(data) {
// do something with the data received
}

我猜测,当连接关闭时,串行端口也会发送信息,因此您可以添加以下内容:

serialport.on("close", closeConnection);

function closeConnection() {
// close the connection internally afterwards
}

虽然最后一部分纯粹是猜测......

在这种情况下,nodejs 应该在建立新连接时触发 open 事件,然后在收到数据时触发 data 事件。如果您要检查用于串行端口的库,可能会有有关如何使用该库的指南

关于javascript - setInterval导致内存溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31564114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com