The following is supposed to check a page for data (a simple integer) every 10 seconds. When the integer exists (data != null), then alert and stop the interval for good).
BUT
Instead it queues up alerts, every 10 seconds. And when the script finally does find the integer it’s looking for, a flood of alerts pops up… one for every ten seconds. If the script lasts 50 seconds, you’ll get 5 alerts all at once 50 seconds after the page loads.
What’s the problem? Shouldn’t the if (data != null) { prevent the alert from triggering at all… until there’s data? I’m at a loss. Plus, “data” never shows up in the alert.
var pinger;
$(document).ready(function() {
var pinger = setInterval(function(){
$.get("/ajax.php", function(data) {
if (data != null) { /** Shouldn't this line stop loops? **/
alert("alert" + data);
clearInterval(pinger);
}
});
}, 10000);
});
/ajax.phptakes more time than the delay at which setInterval() calls your function. So when it ends, setInterval() had actually called the function multiple times.Use setTimeout() instead of setInterval():