The best way for a client to wait for a websocket?

Viewed 7230

I'd like to connect to a server, then do some stuff as soon as the connection is open. But if the connection stalls, I want to trap for that and not do the stuff, and perhaps cancel the waiting connection.

function doStuff () {
    var connection = new WebSocket('wss://someURL');

    //do some stuff here as soon as socket open but trap for stall
}

I was looking for some feature such as

connection.addEventListener('timeout',...);

because upon configuring my WS server to not respond (simulate a too slow server), Chrome's network inspector perpetually shows the connection as "Pending". For lack of that feature, my first pass is:

function doStuff () {
    var connection = new WebSocket('wss://someURL');
    connection.addEventListener('open', onOpen, false);

    var socketTimer = setTimeout(onNotResponding, 10000);

    function onOpen () {
        clearTimeout(socketTimer);
        //do my stuff here.
    }

    function onNotResponding () { 
        //the server is not responding, how do I "cancel" the connection request here? 
    }
}
3 Answers
Related