biplob
biplob

Reputation: 1272

How to stop running timeout jquery function on click and run new function?

I'm trying to update a view with ajax call in every 5 seconds. I've done it in the following way.

function getData(a, b, c) {
    $.ajax({
        url     : 'url',
        success : function(data) {
            $("#result").html(data);
            setTimeout(getData, 5000, a, b, c);
        }
    })
}

$(document).ready(function() {
    getData(1, 2, 3);       
});

$('.btn').click(function(){
    getData(4,5,6);
});

But, in this way as many functions are running as many click.

I need to stop the previous one and run new one or change the parameter of running function.

Upvotes: 3

Views: 1198

Answers (3)

Manjeet Barnala
Manjeet Barnala

Reputation: 2995

Use Ajax abort() function to stop the request when button is clicked and start a new one...

Here i have an example for you, that how abort works... take a look at code and try this...

<script>

var prev_request = false;
var xhr;
var myTimeoutReq;
//var myCondition = true,

function getData(a, b,c,myCondition ) 
{
    if(prev_request == true)
    {
        xhr.abort();
    }

    xhr =  $.ajax({
                url     : 'url',
                beforeSend: function( xhr ) {
                    prev_request = true;
                },
                success : function(data) {
                    $("#result").html(data);
                    if(myCondition == true)
                    {
                        myTimeoutReq = setTimeout(getData, 5000, a, b, c,true);
                    }
                    else
                    {
                        clearTimeout(myTimeoutReq);
                    }   
                },
                complete: function( xhr ) {
                    prev_request = false;
                }
            });
}

$(document).ready(function() {
    getData(1, 2, 3, true);       
});

$('.btn').click(function(){
    getData(4,5,6,false);
});
</script>

Upvotes: 2

pillys
pillys

Reputation: 11

function getData(a, b, c) {
    if(detData.ajax) {
        detData.ajax.abort();
        clearTimeout(getData);
    }
    detData.ajax = $.ajax({
        url     : 'url',
        success : function(data) {
            $("#result").html(data);
            setTimeout(getData, 5000, a, b, c);
        }
    });
}

Upvotes: 1

Adil
Adil

Reputation: 148120

You need to use clearTimeout to finish previous timeout for that you need to assign the setTimeout returned object first. Declare a global object to assign timeout object to that it could be assessed through other functions.

Assigning the timeout object

someGlobalTimeoutObject = setTimeout(getData, 5000, a, b, c);

Clearing timeout object

clearTimeout(someGlobalTimeoutObject);

Upvotes: 2

Related Questions