Mr. Jo
Mr. Jo

Reputation: 5271

AJAX request get's called twice because of an interval

I've a problem with my interval function. This is my function:

let data = {
    action: "verify_status",
};

let interval = setInterval( function () {
    if ( new Date().getTime() - startTime > 600000 ) {
        alert( "Error: Timed out!" );
        clearInterval( interval );
    }

    jQuery.post( ajax_url, data, function () {
    } ).success( function () {
        clearInterval( interval );
        successFunction();
    } ).fail( function ( response ) {
        if ( response.status === 500 ) {
            clearInterval( interval );
        }
    } );
}, 5000 );

My problem is now the following: The interval starts an AJAX request, which now runs in parallel. This is fine as long as the request fails with HTTP 400.

But if it runs successfully, my successFunction() is called. Unfortunately the interval continues running outside. As a result my successFunction() is called twice and sometimes three times, although I interrupt the execution with clearInterval(). Does anyone have an idea how I can do this better?

Upvotes: 0

Views: 475

Answers (2)

ADyson
ADyson

Reputation: 61984

If you don't want the requests to fire in parallel, then don't use an interval. Instead, use a timeout which only runs once. When the AJAX request completes, set a new timeout to trigger the next one. That's a much better way to ensure that there's no overlap.

Something like this:

setTimeout(runAjax, 5000);

function runAjax()
{
  if (new Date().getTime() - startTime > 600000) {
    alert( "Error: Timed out!" );
  }

  jQuery.post(ajax_url, data)
    .success(function () 
    {
      successFunction();
      setTimeout(runAjax, 5000);
    })
    .fail( function ( response ) {
      setTimeout(runAjax, 5000);
    });    
}

Upvotes: 2

salix
salix

Reputation: 861

You cleared the interval with the name verifyPaymentInterval on success. Try clearing the one with the name "interval" as well.

Upvotes: 0

Related Questions