javascript - setInterval导致内存溢出?

标签 javascript node.js setinterval

郑重声明,我的大部分编程都使用 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/

相关文章:

javascript - 谷歌地图 v3 出现扭曲并加倍

javascript - 将 4 行 Jquery 转换为 Mootools

javascript - setInterval 从函数更改背景

JavaScript clearInterval 只能工作一次?

javascript - 如何设置 Express 应用程序的间隔?

javascript - 我的函数没有在 JavaScript 中运行

javascript - (Javascript)如何在两个用户输入的变量之间获取随机数?

node.js - 需要 Jade 内的 javascript 库

css - sass 文件不是由 gulp 编译的

node.js - 检查函数名称是否存在并通过字符串调用