diff --git a/README.md b/README.md index 89b72f1..56039b4 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,11 @@ or - Accepts `integer` - Default: `1000` +#### `maxReconnectInterval` +- The maximum number of milliseconds to delay a reconnection attempt. +- Accepts `integer` +- Default: `30000` + ####`reconnectDecay` - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. - Accepts `integer` or `float` diff --git a/reconnecting-websocket.js b/reconnecting-websocket.js index 4844dfd..8a8fd94 100644 --- a/reconnecting-websocket.js +++ b/reconnecting-websocket.js @@ -79,6 +79,9 @@ * reconnectInterval * - The number of milliseconds to delay before attempting to reconnect. Accepts integer. Default: 1000. * + * maxReconnectInterval + * - The maximum number of milliseconds to delay a reconnection attempt. Accepts integer. Default: 30000. + * * reconnectDecay * - The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. Accepts integer or float. Default: 1.5. * @@ -104,6 +107,8 @@ debug: false, /** The number of milliseconds to delay before attempting to reconnect. */ reconnectInterval: 1000, + /** The maximum number of milliseconds to delay a reconnection attempt. */ + maxReconnectInterval: 30000, /** The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. */ reconnectDecay: 1.5, /** The maximum time in milliseconds to wait for a connection to succeed before closing and retrying. */ @@ -232,10 +237,12 @@ } eventTarget.dispatchEvent(generateEvent('close')); } + + var timeout = self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts); setTimeout(function() { self.reconnectAttempts++; connect(true); - }, self.reconnectInterval * Math.pow(self.reconnectDecay, self.reconnectAttempts)); + }, timeout > self.maxReconnectInterval ? self.maxReconnectInterval : timeout); } }; ws.onmessage = function(event) { diff --git a/reconnecting-websockets.d.ts b/reconnecting-websockets.d.ts index 86af5c7..0acf1a3 100644 --- a/reconnecting-websockets.d.ts +++ b/reconnecting-websockets.d.ts @@ -23,6 +23,9 @@ declare class ReconnectingWebSocket /** The number of milliseconds to delay before attempting to reconnect. */ public reconnectInterval: number; + /** The maximum number of milliseconds to delay a reconnection attempt. */ + public maxReconnectInterval: number; + /** The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist. */ public reconnectDecay: number;