0
$(document).ready(function() {
        $("#test").click( function(){
            test(0,20);
        });
        $("#stop").click( function(){
            // как остановить test();
        });
    });

    test = function (i,max){
        if(i <= max){
            $.ajax({
                type: 'POST',
                url: 'in.php',
                data: {x:'user'},
                dataType: "text",
                cache: false,
                success: function(dat) {
                    console.log(i);
                    test(i+1,max);
                }
            });
        }
    }
1
  • Таким образом остановить не получится, т.к. нет условий для выхода, которыми можно управлять извне.
    – Alex Krass
    17 янв 2014 в 4:37

2 ответа 2

2

Как вариант завести глобальную переменную (или переменную в объекте test) по значению которой будет вызываться функция test или нет. В событии где надо остановить, просто изменять это значение.

$("#stop").click( function(){
    stopFun = true;
    // как остановить test();
});

success: function(dat) {
    console.log(i);
    if (!stopFun) {test(i+1,max)};
}
0
var $ajaxObj = null;
var stop = false;

$(document).ready(function() {
    $("#test").click( function(){
        test(0,20);
    });
    $("#stop").click( function(){
        $ajaxObj.abort();
        stop = true;
    });
});

test = function (i,max){
    if(i <= max && !stop){
        $ajaxObj = $.ajax({
            type: 'POST',
            url: 'in.php',
            data: {x:'user'},
            dataType: "text",
            cache: false,
            success: function(dat) {
                console.log(i);
                if(!stop) test(i+1,max);
            }
        });
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.