发送套接字请求时浏览器内存泄漏

时间:2017-10-23 11:06:04

标签: javascript socket.io

我尝试在服务器上发送websocket请求(socket.io)。请求从浏览器控制台发送。但是我在浏览器中使用脚本时会出现内存泄漏。你会帮助避免内存泄漏,但是要保存脚本 生产率?代码:

var socket = new io;
var counter = 251;

function myNewFunction(data){   
try{
    var IDs = {"items": []};
    var arrayLength = data.items.length;
    var lables = [];
    for (var i = 0; i < arrayLength; i ++){
        if(data.items[i]["amount"] < 20){
            IDs["items"].push(data.items[i]["_id"]);
            lables.push(data.items[i]["amount"]);

}}}catch(err){}

if (IDs["items"].length > 0){
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "url", false);
    xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
    xhr.send(JSON.stringify(IDs));
    if (xhr.status == 200){
        for(var i = 0; i < lables.length; i ++){
            counter -= lables[i];}
        console.log("Left", counter);
    }}
}

setInterval(function(){
    socket.emit("/call/items", {page: 1, sort: 1, search: "", tags: ["1", "2", "3", "4"]}, function(e, data){myNewFunction(data)})
}, 100)

1 个答案:

答案 0 :(得分:0)

应该是这样的:

var socket = new io;
var counter = 251;

function myNewFunction(data) {
    try {
        var IDs = {"items": []};
        var arrayLength = data.items.length;
        var lables = [];
        for (var i = 0; i < arrayLength; i ++) {
            if(data.items[i]["amount"] < 20) {
                IDs["items"].push(data.items[i]["_id"]);
                lables.push(data.items[i]["amount"]);
            }
        }
        if (IDs["items"].length > 0) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "url", false);
            xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
            xhr.send(JSON.stringify(IDs));
            xhr.onreadystatechange = function () {
                if (xhr.status == 200){
                    for(var i = 0; i < lables.length; i ++){
                        counter -= lables[i];}
                    setTimeout(callItems, 100);
                }
            }
        } else {
            setTimeout(callItems, 100);
        }
    } catch(err) {
        setTimeout(callItems, 100);
    }
}

function callItems() {
    socket.emit(
        "/call/items",
        {page: 1, sort: 1, search: "", tags: ["1", "2", "3", "4"]},
        function (e, data) {
            myNewFunction(data)
        }
    );
}

callItems();