简体   繁体   中英

How to stop setInterval in a do while loop in jquery

I want to do is stop setInterval after the do while loop meet the condition.

My problem is even the while loop condition is meet the setInterval is still running.

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

You don't need while loop here at all. In combination with setInterval it doesn't make sense. What you need is probably just 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) {
        }
    });
}

Use clearInterval function to stop interval.

Also note, that setInterval expects function reference as the first argument so this setInterval(Vinformation(), 500) is not correct, because you immediately invoke the Vinformation function.

    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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM