5

I’m working through some code examples for the Diffusion JS API but I don’t understand the example on reconnection. What are the start and abort parameters of the reconnectionStrategy?

// Create a reconnection strategy that applies an exponential back-off
var reconnectionStrategy = (function() {
    return function(start, abort) {
        var wait = Math.min(Math.pow(2, attempts++) * 100, maximumAttemptInterval);

        // Wait and then try to start the reconnection attempt
        setTimeout(start, wait);
    };
})();

// Connect to the server.
diffusion.connect({
    host : 'diffusion.example.com',
    port : 443,
    secure : true,
    principal : 'control',
    credentials : 'password',
    reconnect : {
        timeout : maximumTimeoutDuration,
        strategy : reconnectionStrategy
    }
}).then(function(session) {

Taken from https://github.com/pushtechnology/diffusion-examples/blob/master/js/examples/reconnect.js

John Newby
  • 119
  • 3
  • By the way you could make reconnectionStrategy equal to the function that is returned. It may have previously included its own local variables which would explain why it is the way it is. – Freddie Coleman Jul 07 '16 at 15:12

2 Answers2

4

Those two arguments are described as reconnect and abort in the manual, both are functions that can be put to use.

  • start/reconnect - will initiate a reconnect attempt. Instructs the client to attempt another connection.

  • abort - may be called to abort reconnection, in which case the client will be closed. Call this if you believe further attempts will be fruitless or otherwise undesirable.

With this understanding we see that the example attempts reconnection between waits that increases exponentially (100ms, 200ms, 400ms, etc.) up to a maximum of 60s. If the reconnection attempt fails then the reconnection strategy function is called again.

Martin Cowie
  • 2,788
  • 7
  • 38
  • 74
4

The function also doesn't need to be wrapped:

    var reconnectionStrategy = function(start, abort) {
    var wait = Math.min(Math.pow(2, attempts++) * 100, maximumAttemptInterval);

    // Wait and then try to start the reconnection attempt
    setTimeout(start, wait);};

would do just as well and be less confusing.

Kat
  • 41
  • 3