I'm trying to execute an Ajax call to check if a DB table was updated with some specific new data.
I found part of the solution in this question: instead of using a while
loop (which apparently floods the browser), one should use two independent functions, one of which uses setTimeout(fn,0)
(explanations on why this trick successfully allows Ajax calls not to overlap and flood the browser here and in this video).
My question is: how to force a specific interval of time between each Ajax call? I've tried setting a time superior to 0 (e.g. setTimeout(checkNewData(), 7000);
), but this seems to have no effect on the actual delay between each Ajax call: as soon as one finishes, the next begins.
Note: In the example below I have an on/off switch (stored in autoload_switch
) that can be toggled to interrupt the process
checkNewData() //starts the looping function
function checkIfAutoLoadOn(){
if(autoload_switch === "on")
setTimeout(checkNewData(), 7000);
}
function checkNewData() {
//Check if solutions
$.ajax({
async: true,
type: "POST",
url: "cgi-bin/check_NewData.py",
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
data: JSON.stringify(data_refs),
dataType: "json"
})
.done(function(result) {
if (result["new_data"]==="true") {
// Do sth with data
} else if (result["new_data"]==="false") {
//Check again in some seconds if new data arrived
checkIfAutoLoadOn()
}
})
}