Overwrite asynchronous variable

Asked

Viewed 230 times

0

I need to have control of the number of simultaneous asynchronous ajax calls, but I can’t override the control variable that stores the number of these calls. Every time an asynchronous call is launched it uses the value of the first call (a copy of the variable before the first call I believe).

Follows my code:

var loaderCallStack = [];
var IsLoaderForSubmit = false;
$(document).ready(function() {

    $('a[href="' + window.location.hash + '"]').trigger('click');

    IsLoaderForSubmit = false;
    $(document).ajaxStart(function() {
        loaderCallStack.push("handle");
        if (IsLoaderForSubmit)
        {
            //váriaveis que preciso alterar  aqui
        }
    });
    $(document).ajaxComplete(function() {
        loaderCallStack.pop();
        if (IsLoaderForSubmit && (loaderCallStack.length === 0))
        {
            //váriaveis que preciso alterar  aqui
            IsLoaderForSubmit = false;
        }
    });
});

My question is, do I have a way of controlling the number of calls by keeping the asynchronous code? I know putting it as synchronous would be an option, but right now it’s not what you want.

The solution I thought was to stack something every time the call is made and pop when it’s over. If this minstrel with a control variable cannot be done, there is another way?

1 answer

1


pmargreff, I tried to simulate your problem, I noticed that the ajaxStart is called only on the first request, so use the ajaxSend.

Jsfiddle

var qtdRegistros = 0;    
$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    qtdRegistros++;
    if (qtdRegistros> 1) {
        jqXHR.abort();
    }
});
$(document).ajaxComplete(function(event, jqXHR, ajaxOptions) {
    qtdRegistros--;
});

P.S.: I didn’t create a direct example in the OS, because to simulate this problem I needed to use the Jsfiddle API to simulate the requests.

  • Hello, I switched Start for Send and I kept receiving the same result, the problem is not when detecting sending, the problem happens when I have more than one simultaneous sending.

  • I made a change to the script, I am aborting sending if there is more than one request.

  • worked, thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.