Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, simple polling example

Tags:

jquery

polling

I'm learning jQuery, and I'm trying to find a simple code example that will poll an API for a condition. (ie, request a webpage every few seconds and process the results)

I'm familiar with how to do AJAX in jQuery, I just can't seem to find the "proper" way of getting it to execute on a "timer".

like image 944
Mike Avatar asked Jul 26 '11 19:07

Mike


4 Answers

function doPoll(){
    $.post('ajax/test.html', function(data) {
        alert(data);  // process results here
        setTimeout(doPoll,5000);
    });
}
like image 192
Johnny Craig Avatar answered Nov 06 '22 14:11

Johnny Craig


Here's a (archive.org mirror of a) helpful article on long polling (long-held HTTP request) using jQuery. A code snippet derived from this article:

(function poll() {
    setTimeout(function() {
        $.ajax({
            url: "/server/api/function",
            type: "GET",
            success: function(data) {
                console.log("polling");
            },
            dataType: "json",
            complete: poll,
            timeout: 2000
        })
    }, 5000);
})();

This will make the next request only after the ajax request has completed.

A variation on the above that will execute immediately the first time it is called before honouring the wait/timeout interval.

(function poll() {
    $.ajax({
        url: "/server/api/function",
        type: "GET",
        success: function(data) {
            console.log("polling");
        },
        dataType: "json",
        complete: setTimeout(function() {poll()}, 5000),
        timeout: 2000
    })
})();
like image 44
chrisjleu Avatar answered Nov 06 '22 13:11

chrisjleu


From ES6,

var co = require('co');
var $ = require('jQuery');

// because jquery doesn't support Promises/A+ spec
function ajax(opts) {
  return new Promise(function(resolve, reject) {
    $.extend(opts, {
      success: resolve,
      error: reject
    });
    $.ajax(opts);
  }
}

var poll = function() {
  co(function *() {
    return yield ajax({
      url: '/my-api',
      type: 'json',
      method: 'post'
    });
  }).then(function(response) {
    console.log(response);
  }).catch(function(err) {
    console.log(err);
  });
};

setInterval(poll, 5000);
  • Doesn't use recursion (function stack is not affected).
  • Doesn't suffer where setTimeout-recursion needs to be tail-call optimized.
like image 14
Boopathi Rajaa Avatar answered Nov 06 '22 12:11

Boopathi Rajaa


function poll(){
    $("ajax.php", function(data){
        //do stuff  
    }); 
}

setInterval(function(){ poll(); }, 5000);
like image 11
genesis Avatar answered Nov 06 '22 12:11

genesis