简体   繁体   English

setTimeout 立即调用函数而不是延迟调用

[英]setTimeout calls function immediately instead of after delay

I want to make a value on an HTML page that will be updated every 5 seconds so as to not overwhelm the server.我想在 HTML 页面上创建一个值,该值将每 5 秒更新一次,以免使服务器不堪重负。 It turns out that setTimeout() inside my function is not delaying properly, but is instead being called immediately.事实证明,我的函数中的 setTimeout() 没有正确延迟,而是立即被调用。 Can someone help me find a clue?有人可以帮我找到线索吗? I really don't want to give my server too much work because I have to implement a lot more AJAX.我真的不想让我的服务器做太多工作,因为我必须实现更多的 AJAX。

Here's the code:这是代码:

window.onload = function GetUsersNumber() {
    aside = document.getElementById("users");
    if (XMLHttpRequest) var x = new XMLHttpRequest();
    else var x = new ActiveXObject("Microsoft.XMLHTTP");
    x.open("GET", "users_count.php", true);
    x.send();
    x.onreadystatechange = function () {
        if (x.readyState == 4) {
            if (x.status == 200) aside.innerHTML = x.responseText;
            setTimeout(GetUsersNumber(), 50000);
        }
    }
}

setTimeout takes a function as parameter. setTimeout 接受一个函数作为参数。 What you are doing is executing the function right away and passing is returned value of the exected function.您正在做的是立即执行函数并传递执行函数的返回值。 Pass GetUsersNumber instead of GetUsersNumber() .传递GetUsersNumber而不是GetUsersNumber() () will already execute the function. () 将已经执行该函数。

setTimeout(GetUsersNumber, 50000);

On a side note:旁注:

  • Most of the modern browsers support XMLHttpRequest natively.大多数现代浏览器本身都支持 XMLHttpRequest。 So, using ActiveXObject is not required.因此,不需要使用 ActiveXObject。
  • For older browsers, the if condition will anyways give error.对于较旧的浏览器, if 条件无论如何都会出错。 Do this: if(window.XMLHttpRequest)这样做: if(window.XMLHttpRequest)

A function object in JavaScript is one thing. JavaScript 中的函数对象是一回事。 A function call is a different thing.函数调用是另一回事。 You're using the latter, by including parentheses after the function name*, but you need the former, without parentheses.您正在使用后者,方法是在函数名称 * 之后包含括号,但您需要前者,没有括号。 This allows setTimeout to later invoke the function itself by using the passed-in object.这允许setTimeout稍后使用传入的对象调用函数本身。 Assuming you do actually want 5 seconds (rather than the 50 seconds the original code was using):假设您确实需要 5 秒(而不是原始代码使用的 50 秒):

setTimeout(GetUsersNumber, 5000);

* Really, any old variable that holds a function object can be invoked like that, but for convenience, defining a function also defines a variable name for it. *实际上,任何持有函数对象的旧变量都可以这样调用,但为了方便起见,定义函数还为其定义了变量名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM