clearInterval inside setInterval, unable to break loop, with jquery and .post()

删除回忆录丶 提交于 2019-12-24 08:35:53

问题


I'm trying to call clearInterval inside setInterval function, which is doing some ajax fetching, without any luck.

var nre = setInterval('checkit()',5000);
$(function() {
    checkit = function(){
        $.post("check.php", { login: "<?php echo $_SESSION['login'];?>" }, function( data ) {
            if (data == 1) {
                $('#debug').html(data);
                window.clearInterval(nre);
            }

        });
    }
});

The point is, that the loop wont break, although recieves positive data to do so.

I've read that async action of setInterval function might be the issue here. Is there a better way to solve it?


回答1:


Move everything inside the same scope, and don't use the string form of setInterval:

$(function() {
    var nre = setInterval(checkit, 5000);
    function checkit() {
        $.post("check.php", { login: "..." }, function( data ) {
            if (data === 1) {
                $('#debug').html(data);
                clearInterval(nre);
            }
        });
    }
});



回答2:


checkit won't be visible outside the document.ready so move the setInterval call inside the document.ready.

If you would like to assign an anonymous function to the variable checkit, then you will have to move the setInterval call after the variable is assigned.

$(function() {
    var checkit = function(){
        $.post("check.php", { login: "<?php echo $_SESSION['login'];?>" }, function( data ) {
            if (data == 1) {
                $('#debug').html(data);
                window.clearInterval(nre);
            }

        });
    }
   var nre = setInterval(checkit,5000);
});

Or, if you declare the function, then you can call setInterval before the function declaration.

$(function() {
    var nre = setInterval(checkit, 5000);
    function checkit() {
        $.post("check.php", { login: "..." }, function( data ) {
            if (data == 1) {
                $('#debug').html(data);
                clearInterval(nre);
            }
        });
    }
});


来源:https://stackoverflow.com/questions/10280997/clearinterval-inside-setinterval-unable-to-break-loop-with-jquery-and-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!