D
D
Dmitry Makarov2016-11-14 09:51:44
JavaScript
Dmitry Makarov, 2016-11-14 09:51:44

Websocket reconnect slows down in Firefox. Why is that? How to overcome?

Hello colleagues!
I implement communication with the server using WebSockets.
According to the plan, there should be an automatic reconnect.
I do it with code like this:

"use strict";

let webSocket = undefined;
let timer = 0;

function Link (url) {
  function startWebSocket () {
    if (webSocket !== undefined) return;

    webSocket = new WebSocket(url);

    webSocket.onmessage = event => console.log(event);
    webSocket.onopen = () => { 
      if (timer === 0) return;
      clearInterval(timer);
      timer = 0;
    };
    webSocket.onclose = () => {
      webSocket = undefined;
      if (timer === 0) timer = setInterval(startWebSocket, 1000);
    };
  }

  function sendMessage (message) {
    if (webSocket === undefined) return;
    webSocket.send(message);
  }

  return {
    send: sendMessage,
    start: startWebSocket
  };
}

export default Link;

Removed everything from the code. There is also preprocessing of received messages and the generation of events for opening / closing / error / received message, but this is not relevant.
There is a problem. In Firefox. After about 10 connection attempts, the pause between attempts increases to 30 seconds or more. In Chrome, this is not observed.
Is this a bug or a feature?
How to overcome such behavior?
UPD: in the comment I described in detail: how, in my opinion, the code works.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question