需要一个延迟功能javascript [英] Need a delay function javascript

查看:28
本文介绍了需要一个延迟功能javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi im currently making a xmhhttp request, but the site takes some time to load, so I only get the 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);
  }

推荐答案

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

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

不过有两点:

  • 无论readyState 是什么,checkState 函数都会返回,因此请确保您只在回调中执行依赖于它的操作,而不是之后.
  • 如果 readyState 和 status 从未获得您想要的值,那么您就不走运了(但您可以扩展该函数以接受将处理超时情况的第二个回调).

这篇关于需要一个延迟功能javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆