setInterval导致内存溢出

setInterval causing a memory overflow?

本文关键字:溢出 内存 setInterval      更新时间:2023-09-26

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

的指南。