如何外部暂停和停止递归javascript函数

Suy*_*ash 2 javascript jquery

我有一个函数,它以2秒的暂停调用自己,直到ajax调用返回0.现在它可以持续很长时间,因此我希望暂停它或使用外部事件(如按钮单击)停止它.

function create_abcd()
{
    var dataString = 'action=create_abcd&type=' + $('#abcd_type').val() + '&count=100';
    $.ajax({
        type: "POST",
        url: "backend.php",
        data: dataString,
        success: function(msg){
            if(msg != "0")
            {
                $("#abcd_output").append('<p>' + msg + '</p>')
                    setTimeout(create_abcd, 2000);
            }
            else
                return false;
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

Pie*_*rre 7

就像是:

var needStop = false;

function create_abcd()
{
    var dataString = 'action=create_abcd&type=' + $('#abcd_type').val() + '&count=100';
    $.ajax({
        type: "POST",
        url: "backend.php",
        data: dataString,
        success: function(msg){
            if(needStop) {
                needStop = false;
                return;
            }
            if(msg != "0")
            {
                $("#abcd_output").append('<p>' + msg + '</p>')
                    setTimeout(create_abcd, 2000);
            }
            else
                return false;
        }
    });
}

$('#button').click(function() {
    needStop = true;
});
Run Code Online (Sandbox Code Playgroud)

=)