setInterval导致内存溢出?

setInterval causing a memory overflow?

郑重声明,我在很多编程中都使用 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 事件。如果您要检查串口使用的是哪个库,可能会有关于如何使用该库的指南