Search code examples
javascriptpolling

Javascript poller does not start immediately


in my javascript I defined a poller in order to refresh some contents every second. The definition is the following:

var poller = {
    // number of failed requests
    failed: 0,

    // starting interval - 1 seconds
    interval: 1000,

    // kicks off the setTimeout
    init: function() {
        setTimeout(
            $.proxy(this.getData, this), // ensures 'this' is the poller obj inside getData, not the window object
            this.interval
        );
    },

    // get AJAX data + respond to it
    getData: function() {
        var self = this;

        $.ajax({
            url: "api/view",
            success: function(response) {

                   // ....do something....

                    // recurse on success
                    self.init();
                }
            },

            error: $.proxy(self.errorHandler, self)
        });
    },

    // handle errors
    errorHandler: function() {
        if (++this.failed < 10) {

            this.interval += 1000;

            // recurse
            this.init();
        }
      }
    };

    poller.init();
});

The problem is that it does not start immediately when the page is loaded. Does anyone know the reason why? Many thanks in advance!


Solution

  • This is happening because of the response time from the 1st $.ajax call. When calling a service in localhost (dev environment), calls may sometimes take more than 40 seconds.

    Also, please see if any other element, such as Highcharts you are using in your specific page, cause any delay on loading the page.

    You can examine this behavior in your browser's developer console, under Network. Here is an example of the response time of one of my $.ajax calls (I'm using Google Chrome):

    enter image description here

    I also suspect that when you move this to production, your response times will be much lower, but you will have to take into consideration that 1000 milliseconds might be too aggressive on your server.