HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

A reusable AJAX polling function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
reusableajaxfunctionpolling

Problem

I have written a small JavaScript function which performs an AJAX request every x seconds.

I was hoping some of you could give it a look over and give me any pointers on redundant code or bad practices.

The idea of the function is to:

  • Allow for polling to be initiated



  • Once initiated, poll once every x seconds and perform an AJAX request.



  • Stop polling once disablePolling() is executed.



  • Be able to be reused anywhere.



requester.js

function Request() {

this.poll = false;

this.activatePoll = function () {
    this.poll = true;
    this.runPoll();
};

this.disablePoll = function () {
    this.poll = false;
};

this.runPoll = function () {
    var self = this;
    var poll = setTimeout(function () {
        $.ajax({
            url: './request.php',
            success: function (response) {
                console.log(response);
            },
            dataType: "json",
            complete: function () {
                if (self.poll == false) {
                    clearTimeout(poll);
                } else {
                    self.runPoll();
                }
            }
        })
    }, 1000);
};
}


Usage:


index.html


    
    Requester

Requester

    
    
    

    $(document).ready(function () {
        $request = new Request();
    });




request.php



It should also be mentioned that theAajax request will need to also POST some parameters.

Solution

-
Your code is simply a GET request, so the shorthand getJSON can be used for this.

-
Instead of success and complete, use the more standard Promise method then.

-
Instead of a recursive setTimeout, use setInterval instead. This avoids your code from rescheduling a callback on each iteration. You can always clear interval timers with clearInterval.

-
When using setInterval, clearing the timer will suffice for stopping the polling. You don't need the boolean flag to tell you to stop.

-
When using setInterval, you don't need an extra function for a recursive call anymore.

-
You also seem to use OOP. It is normally advised to put methods on the prototype and not the instance so that methods are shared per instance and not created per instance.

-
It is usually not advised to use inline scripts. Use addEventListener to bind your click handlers.

-
Booleans are usually prefixed with an is, has or are depending on the grammar. This is to not mistake a property as some other non-boolean value.

-
Put the url and interval in a variable that acts as a constant. That way, you can easily configure as well as spot the values and not dig through code.

-
If ES6 is available for you, self = this can be taken care of by using arrow functions.

In the end, your code could be as simple as

function Request() {
  this.pollTimer = null;
  this.interval = 1000;
  this.url = './request.php';
}

Request.prototype.disablePoll = function () {
  clearInterval(this.pollTimer); 
  this.pollTimer = null;
};

Request.prototype.activatePoll = function () {
  this.pollTimer = setInterval(() => {
    $.getJSON(this.url).then(response => console.log(response))
  }, this.interval);
};

Code Snippets

function Request() {
  this.pollTimer = null;
  this.interval = 1000;
  this.url = './request.php';
}

Request.prototype.disablePoll = function () {
  clearInterval(this.pollTimer); 
  this.pollTimer = null;
};

Request.prototype.activatePoll = function () {
  this.pollTimer = setInterval(() => {
    $.getJSON(this.url).then(response => console.log(response))
  }, this.interval);
};

Context

StackExchange Code Review Q#121802, answer score: 5

Revisions (0)

No revisions yet.