首页 > 解决方案 > 发出Ajax请求时如何只等待1秒,但等待时间后不取消请求?

问题描述

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

例子:

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

标签: javascriptjqueryajaxasynchronoussettimeout

解决方案


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

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

或者设置一个标志,你可以取消 timeout

请注意,您的call函数不会返回任何内容。相反,您基本上处理事件(请求完成或超时到期中的一个或两个)。


推荐阅读