Skip to content

Instantly share code, notes, and snippets.

@linusthe3rd
Last active June 30, 2022 15:21
Show Gist options
  • Save linusthe3rd/9310539 to your computer and use it in GitHub Desktop.
Save linusthe3rd/9310539 to your computer and use it in GitHub Desktop.

Revisions

  1. linusthe3rd revised this gist May 6, 2014. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion exponentialBackoff.js
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,7 @@
    var attempts = 1;

    function createWebSocket () {
    var connection = new WebSocket();
    var attempts = 1;

    connection.onopen = function () {
    // reset the tries back to 1 since we have a new connection opened.
  2. linusthe3rd created this gist Mar 2, 2014.
    34 changes: 34 additions & 0 deletions exponentialBackoff.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    function createWebSocket () {
    var connection = new WebSocket();
    var attempts = 1;

    connection.onopen = function () {
    // reset the tries back to 1 since we have a new connection opened.
    attempts = 1;

    // ...Your app's logic...
    }

    connection.onclose = function () {
    var time = generateInterval(attempts);

    setTimeout(function () {
    // We've tried to reconnect so increment the attempts by 1
    attempts++;

    // Connection has closed so try to reconnect every 10 seconds.
    createWebSocket();
    }, time);
    }
    }

    function generateInteval (k) {
    var maxInterval = (Math.pow(2, k) - 1) * 1000;

    if (maxInterval > 30*1000) {
    maxInterval = 30*1000; // If the generated interval is more than 30 seconds, truncate it down to 30 seconds.
    }

    // generate the interval to a random number between 0 and the maxInterval determined from above
    return Math.random() * maxInterval;
    }