I have currently got the following code which will run a bunch of ajax requests (40-50) then do them all again. (So do them forever essentially)
Code:
$(document).ready(function () {
window.setInterval(function () {
$('div.env').each(function (index, item) {
var vm = $(item).text();
var env = "http://localhost:56656/HTML" + vm + ".htm";
$.ajax(env, {
async: false,
URL: env,
type: "GET",
dataType: "html",
success: function (data) {
//alert("Colouring");
var style = $(data).filter('div').attr('style');
var styleObj = {};
$.each(style.split(';'), function () {
var rule = this.split(':');
styleObj[$.trim(rule[0])] = $.trim(rule[1]);
});
$(item).css('background', styleObj.background);
},
error: function () {
$(item).css('background', '#f00');
}
});
});
}, 10000);
});
As you can see, I am currently using Timeouts which are running particularly slow on IE and on occasion running slow on chrome. When I say slow, I mean that all the ajax requests will complete then the screen will refresh with the updates. This is the case on IE all the time and occasionally Chrome. Ideally, I would like the ajax to do its requests, update then do the next ajax request.
Any better way to do AJAX requests continually?
Thank you in advance, James
You may want to use Caolan's async library. You're code may look like this (after including async.js of course):
$(document).ready(function () {
function call() {
var calls = [];
$('div.env').each(function (index, item) {
calls.push(function(callback) {
$.ajax({
// DO NOT USE async: false!!!!
// some ajax settings
complete : function() {
callback();
}
});
});
});
async.parallel(calls, function() {
/* This will fire when every call finishes.
You may want to add timeout here, or else
you will end up flooded with requests. */
call();
});
};
});
You should tune it to your needs (async can handle errors as well, read the documentation). You said that you want them to fire one after another, so use async.series instead of async.parallel.
BTW This piece of code:
$.ajax({
async: false
PURE EVIL!!! Blocks every other script and even entire browser!!! That's probably the reason for your "slow-and-blink" problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With