Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to externally pause and stop recursive javascript function

I have a function which calls itself with a pause of 2 seconds until the ajax call returns 0. Now it can go on for a long time, hence i wish to pause it or stop it with an external event like a button click.

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

any help would be greatly appreciated!

like image 730
Suyash Avatar asked Mar 15 '26 16:03

Suyash


1 Answers

Something like:

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

=)

like image 96
Pierre Avatar answered Mar 17 '26 04:03

Pierre