开发者

Need a delay function javascript

开发者 https://www.devze.com 2023-02-07 18:10 出处:网络
Hi im currently making a xmhhttp request, but the site takes some time to load, so I only get the开发者_StackOverflow社区 ReadyState = 3 and status = 200. So I need something that waits until the read

Hi im currently making a xmhhttp request, but the site takes some time to load, so I only get the开发者_StackOverflow社区 ReadyState = 3 and status = 200. So I need something that waits until the readystate = 4, but I want to limit this function so that it only checks once a second if the readystate = 4, else do nothing.

How can such a delay function look like?

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


Why would you invent the wheel ?

You should just pass a handler to the XHRs onreadystatechange callback.

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


A setInterval might do the trick if I understand you correctly:

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


We can write a function for checking the state of your xmlhttp-object:

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

Then you can use it like this:

checkState(xmlhttp, function(whatever, arguments, you, need) {
  // the code here will be run when the readyState is 4 and the status is 200
});

Two things though:

  • The checkState function will return regardless of the readyState, so make sure you only do things that depend on it in the callback, not after.
  • If the readyState and status never get your desired values, you're out of luck (but you could extend the function to accept a second callback that will handle a timeout case).


Maybe use something like

Edit: use the onreadystatechange:

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

精彩评论

暂无评论...
验证码 换一张
取 消