Periodically send ajax requests

ajax, javascript, jquery, ruby, ruby-on-rails

Solution

Since there is essentially an unknown delay between the time you send out an AJAX request and the time you receive a complete response for it, an oftentimes more elegant approach is to start the next AJAX call a fixed amount of time after the prior one finishes. This way, you can also ensure that your calls don't overlap.

var set_delay = 5000,
    callout = function () {
        $.ajax({
            /* blah */
        })
        .done(function (response) {
            // update the page
        })
        .always(function () {
            setTimeout(callout, set_delay);
        });
    };

// initial call
callout();

Problem

There is a page and I want periodically to make "background" ajax requests. So the page is loaded then it should send ajax requests in a certain amount of time. I might use cron for that. I have never use previously so I'm wondering if it would fit for that task. Is there any other more simple way? P.S. The time delay will be about 5 minutes.

Original source

Related problems