1

I have a situation where i have to return false if ajax request does not return within 1 second. But process the response after the request has been completed. Using Ajax timeout does not work for me because, it cancels the request after that time. But i want the response even if it takes long time.

Example:

function call(){
  ajax.request(...)
     if(does not respond in 1 second)
        immediately return false and wait for response
     else
        return response
}
JSGeek
  • 93
  • 6

1 Answers1

3

You need to set up a race between your request finishing and your handler for the error. If the request finishes first, set a flag that you check before handling the error:

function call(){
  let finished = false;
  function callback(){ 
    finished = true 
    // your callback code goes here
  };
  ajax.request(..., callback) // make sure this is an async request
  function handleTimeout() {
    if (finished) return;
    // your timeout code goes here
  }
  setTimeout(handleTimeout, TIMEOUT_IN_MILLISECONDS);
}

alternatively to setting a flag, you could cancel the timeout.

Notice that your call function doesn't return anything. Instead, you essentially handle events (either or both the request completing or the timeout expiring).

Garrett Motzner
  • 3,021
  • 1
  • 13
  • 30
  • Thanks. This works perfectly. The mistake i made is that i kept async:false which dint do the obvious. :) – JSGeek Jan 24 '19 at 22:15