-->

里面的setInterval clearInterval,无法打破循环,使用jQuery和。员额()

2019-10-16 15:10发布

我试图调用clearInterval setInterval函数,这是做一些Ajax取里面,没有任何的运气。

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);
            }

        });
    }
});

问题的关键是,环路不会打破,虽然临危利好数据这样做。

我读过setInterval函数的异步操作可能是这里的问题。 有没有更好的办法来解决呢?

Answer 1:

将一切的同一范围内,并且不使用的字符串形式setInterval

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


Answer 2:

checkit将不可见之外document.ready所以移动setInterval内部通话document.ready

如果你想一个匿名函数赋值给变量checkit,那么你将有变量赋值后,移动电话的setInterval。

$(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);
});

或者,如果你声明的功能,那么你可以调用setInterval函数声明之前。

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


文章来源: clearInterval inside setInterval, unable to break loop, with jquery and .post()