嗨,我目前正在发出一个 xmhhttp 请求,但该站点需要一些时间来加载,所以我只得到 ReadyState = 3 和 status = 200。所以我需要等待直到 readystate = 4 的东西,但我想限制这个功能如果readystate = 4,它只每秒检查一次,否则什么都不做。

这样的延迟函数会是什么样子?

   if (xmlhttp.readyState==4 && xmlhttp.status==200)//Add the delay here so that the else doesn't occur
    {
    var txt=xmlhttp.responseText;
    .....
  else {

    document.write("status: " + xmlhttp.readyState + " " + xmlhttp.status);
  }

最佳答案

我们可以编写一个函数来检查 xmlhttp 对象的状态:

var checkState = function(xmlhttp, callback) {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    callback(whatever, arguments, that, you, want, to, send);
  } else {
    // Check back again 1 sec later
    setTimeout(checkState, 1000);
  }
};

然后你可以像这样使用它:
checkState(xmlhttp, function(whatever, arguments, you, need) {
  // the code here will be run when the readyState is 4 and the status is 200
});

不过有两点:
  • checkState 函数会在不管 readyState 的情况下返回,所以确保你只在回调中做依赖于它的事情,而不是之后。
  • 如果 readyState 和 status 从未获得您想要的值,那么您就不走运了(但您可以扩展该函数以接受将处理超时情况的第二个回调)。
  • 关于javascript - 需要一个延迟功能javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4864471/

    10-14 19:36
    查看更多