如何在jquery中的do while循环中停止setInterval

时间:2014-07-27 08:13:26

标签: javascript jquery html ajax setinterval

我想做的是在do while循环满足条件后停止setInterval。

我的问题是即使while循环条件满足setInterval仍在运行。

do
{
setInterval(
Vinformation();
,500);
}while($('#emailCodeResult').val() !='')

function Vinformation(){
   var data = {};
        data.emailCodeResult = $('#emailCodeResult').val();

    $.ajax({
        type: "POST",
        url: "Oppa.php",
        data: data,
        cache: false,
        dataType:"JSON",
        success: function (result) {



        }
     });
            return false;
}

2 个答案:

答案 0 :(得分:5)

您根本不需要while循环。结合setInterval它没有意义。你需要的只是setInterval

var interval = setInterval(Vinformation, 500);

function Vinformation() {

    if ($('#emailCodeResult').val() == '') {
        clearInterval(interval);
        return;
    }

    var data = {};
    data.emailCodeResult = $('#emailCodeResult').val();

    $.ajax({
        type: "POST",
        url: "Oppa.php",
        data: data,
        cache: false,
        dataType: "JSON",
        success: function (result) {
        }
    });
}

使用clearInterval功能停止间隔。

另请注意,setInterval期望函数引用作为第一个参数,因此setInterval(Vinformation(), 500)不正确,因为您立即调用Vinformation函数。

答案 1 :(得分:3)

    var itvl1= window.setInterval(function(){
        Vinformation();
    },500);

    function Vinformation(){
        var data = {};
        data.emailCodeResult = $('#emailCodeResult').val();

        if(data.emailCodeResult  !=''){
            window.clearInterval(itvl1);
        };

        $.ajax({
            type: "POST",
            url: "Oppa.php",
            data: data,
            cache: false,
            dataType:"Jenter code hereSON",
            success: function (result) {

            }
        });
        return false;

}