如何在Ajax请求时只等待1秒,等待时间过后不取消请求?

How to wait only for 1 second when Ajax Request is made, but don't cancel the request after wait time?

我有一种情况,如果 ajax 请求在 1 秒内没有 return,我必须 return false。但是在请求完成后处理响应。使用 Ajax 超时对我不起作用,因为它会在该时间后取消请求。但我想要回应,即使需要很长时间。

示例:

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

您需要在请求完成和错误处理程序之间设置一个竞赛。如果请求先完成,请设置一个标志,以便在处理错误之前检查:

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

除了设置标志,您还可以 cancel the timeout

请注意,您的 call 函数没有 return 任何内容。相反,您实际上是在处理事件(请求完成或超时到期)。