建立WebSockets连接时100%的CPU消耗

时间:2013-02-11 03:40:14

标签: javascript performance websocket cpu-usage readystate

我尝试编写一个连接到WebSocket服务器的函数。此服务器关闭时会出现此问题。此功能应该等待它,即使很长一段时间,但它不应该消耗100%的CPU。这是我的代码:

var state = {
    connected: false
};

var settings = {
    host: 'localhost',
    port: 1988
};

function connect(settings) {
    try {
        var socket;
        var host = 'ws://' + settings.host + ':' + settings.port;
        var socket = new WebSocket(host);

        socket.onopen = function() {
            state.connected = true;
        }
        // socket.onmessage
        socket.onclose = function() {
            state.connected = false;
            connect(settings);
        }

    } catch(e){
        console.log(e);
    }
}

所以我需要以某种方式将间隔传递给WebSocket构造函数,看起来它只是试图在循环中打开连接,从而破坏性能。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

当您尝试连接时,套接字立即关闭,导致您再次尝试连接。在尝试之间添加间隔:

socket.onclose = function() {
    state.connected = false;
    setInterval(function() {
        connect(settings);
    }, 1000);
}