开发者

Why does this js if clause not stop looping?

开发者 https://www.devze.com 2023-04-03 06:27 出处:网络
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).

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, "d开发者_JAVA技巧ata" 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.php takes 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():

$(document).ready(function() {
    setTimeout(function self(){
        $.get("/ajax.php", function(data) {
            if (data != null) {
                alert("alert" + data);
            } else {
                setTimeout(self, 10000);
            }
        });
    }, 10000);
});


My bet is that you don't get a null from $.get (even if there's an empty string then comparing it to null returns true - '' != null return true). That's why the alerts are poping-up.

Also, some made a good point, that if your ajax call takes more than a 10 seconds it would fire another time, even though previous ajax might return correct data that suppose to stop the loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号