Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var attempts = 1;
function createWebSocket () {
var connection = new WebSocket();
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;
}
@ds0nt

This comment has been minimized.

Copy link

ds0nt commented Feb 27, 2015

// one liner for cool people
function generateInterval (k) {
  return Math.min(30, (Math.pow(2, k) - 1)) * 1000; 
}
@JohnMaguire

This comment has been minimized.

Copy link

JohnMaguire commented Apr 28, 2015

All ye' who enter: Beware the typo on line 26. generateInteval should be generateInterval.

@lap00zza

This comment has been minimized.

Copy link

lap00zza commented Sep 26, 2016

👍

@kryhtin

This comment has been minimized.

Copy link

kryhtin commented Feb 14, 2017

Reconnection will happen only once, use setInterval instead setTimeout

@kenan2002

This comment has been minimized.

Copy link

kenan2002 commented May 18, 2017

@ds0nt
Your one-line code lack a random number generate process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.