Currently, I’m using setInterval to run several AJAX functions that call PHP pages like so –
var intervalOne = setInterval(ajaxfunction, 1500);
This works fine on a test server with a tiny response time. However occasionally on my live server, there will be a bit of lag and the interval time will come again before the first one has finished, repeating the same call, and causing duplicate data to appear.
Is there any way to keep the same interval time, but have it wait to call the function if the first one hasn’t finished yet?
Alternatively, Is there anything I can put in a readystate portion of the AJAX calls to have them trigger themselves again once they are complete?
Edit – Example of one of my ajax calls:
function Send() {
var name = document.getElementById('name').value;
var message = document.getElementById('message').value;
var xmlhttp = getXMLHttp();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4)
{
document.getElementById('message').value = "";
if(xmlhttp.responseText != "") {
var chat = document.getElementById('messagebox');
chat.innerHTML = chat.innerHTML + '<div class=\"alert\">' + xmlhttp.responseText + '</div>';
chat.scrollTop = 1000000000;
}
}
}
xmlhttp.open("POST","submit_message.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=" + name + "&message=" + message);
}
The easy way is through blindly reapplying
setTimeoutat the end of your process:This would wait 1500ms between your processes. Like this: 300ms process, 1500ms wait, 2000ms process, 1500ms wait, 400ms process, 1500ms wait…
A bit more closely to what you want, you could reapply
setTimeoutat the beginning of your process. In this case, you’d get: 300ms process, 1200ms wait, 2000ms process, 0ms wait, 400ms process, 1100ms wait… The problem that happens withsetIntervaldoesn’t happen here, because this only schedules the next iteration, not all future ones. Notice also that since JS is single-threaded, an event can’t interrupt itself like you could get in some other languages.And yeah, I guess it’s more popular these days to make it self-executing, as you can see in some answers; but that’s just aesthetics, the end effect is the same.