需要一个延迟函数的Javascript

4

你好,我目前正在进行一项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);
  }
4个回答

4

你为什么要重新发明轮子?

你只需要将处理程序传递给XHRsonreadystatechange回调函数即可。

xmlhttp.onreadystatechange = function() {
     switch( xmlhttp.readyState ) {
          case 4: {
              if (xmlhttp.status === 200) {
                  var txt = xmlhttp.responseText; // or do something else here
              }
              break;
          }
          case 3: {
              // go interactive !
              break;
          }
     }
};

2
如果我理解正确,setInterval 可能会解决问题:
var seconds = 0;
var interval = setInterval(function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        // Stop checking
        clearInterval(interval);
        // Ready
        var txt = xmlhttp.responseText;

    } else if (++seconds > 10) { // Do we give up?
        clearInterval(interval);
        // Give up

    }
}, 1000); // Checks once every second

0
我们可以编写一个函数来检查您的XMLHttpRequest对象的状态:
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 永远无法达到你想要的值,那就没有办法了(但你可以扩展该函数以接受第二个回调函数来处理超时情况)。

-2

或许可以使用类似的东西

编辑:使用onreadystatechange:

Connection.onreadystatechange = function()
{
    if (Connection.readyState != 4)
    {
        return;
    }
    else
    {
        // do your thing
    }
};

这不是一个答案,你几乎是复制了问题本身。他正在询问如何执行“等待一会儿”的部分 :) - Jakob
嗯,是的。为什么我错过了那个问题超出了我的理解。马上回来,修复它 :P - Zsub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接