Polling a server using Ajax and Dojo

I use dojo.xhrPost to send Ajax requests. The
call ends withfunction sendRequest()

Now I constantly (every 3 seconds) send the same ajax messages to the server.

How can I poll the server using Dojo? I basically need to call sendRequest()every 3 seconds

+3
source share
3 answers

I don’t think that Dojo has a built-in method for polling, so here we use the general method that is used within the frameworks

var Poll = function(pollFunction, intervalTime) {
    var intervalId = null;

    this.start = function(newPollFunction, newIntervalTime) {
        pollFunction = newPollFunction || pollFunction;
        intervalTime = newIntervalTime || intervalTime;

        if ( intervalId ) {
            this.stop();
        }

        intervalId = setInterval(pollFunction, intervalTime);
    };

    this.stop = function() {
        clearInterval(intervalId);
    };
};

Using:

var p = new Poll(function() { console.log("hi!"); }, 1000);
p.start();
setTimeout(function() { p.stop();}, 5000);

Or in your case:

var p = new Poll(sendRequest, 3000);
p.start();

If you want this as a Dojo package, then this is a trivial extension:

dojo.provide("Poll");

dojo.declare("Poll", null, {
    intervalId:   null,
    pollFunction: null,
    intervalTime: null,

    constructor: function(newPollFunction, newIntervalTime) {
        this.pollFunction = newPollFunction;
        this.intervalTime = newIntervalTime;
    },

    start: function(newPollFunction, newIntervalTime) {
        this.pollFunction = newPollFunction || this.pollFunction;
        this.intervalTime = newIntervalTime || this.intervalTime;

        this.stop();
        this.intervalId = setInterval(this.pollFunction, this.intervalTime);
    },

    stop: function() {
        clearInterval(this.intervalId);
    }
});

Using:

var p = new Poll(function() {console.log("hi");}, 250);
p.start();
setTimeout(dojo.hitch(p, p.stop), 1000);
+3

, :

  • , ()
  • setInterval , , ( ) (); , ; .
  • ; ,
  • , , xhr, , - , , (, iPad)
  • xhr, xhrGet

, , , xhr .

0

To constantly update the grid, you can include your ajax request in the refresh-complete grid callback function.

yourGrid.on('dgrid-refresh-complete', function(event) { 

//Ajax request fireing every 3 sec


}
0
source

Source: https://habr.com/ru/post/1737175/


All Articles