setTimeout立即调用函数而不是延迟后调用 [英] setTimeout calls function immediately instead of after delay

查看:183
本文介绍了setTimeout立即调用函数而不是延迟后调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在HTML页面上创建一个值,该页面将每5秒更新一次,以免压倒服务器。事实证明,我的函数中的setTimeout()没有正确延迟,而是立即被调用。有人能帮我找到线索吗?我真的不想给我的服务器太多工作,因为我必须实现更多的AJAX。

I want to make a value on an HTML page that will be updated every 5 seconds so as to not overwhelm the server. It turns out that setTimeout() inside my function is not delaying properly, but is instead being called immediately. 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.

这是代码:

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


推荐答案

JavaScript中的函数对象是一回事。功能调用是另一回事。你正在使用后者,在函数名*之后加上括号,但你需要前者,没有括号。这允许 setTimeout 以后通过使用传入的对象来调用函数本身。假设你确实想要5秒(而不是原始代码使用的50秒):

A function object in JavaScript is one thing. 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. Assuming you do actually want 5 seconds (rather than the 50 seconds the original code was using):

setTimeout(GetUsersNumber, 5000);

* 实际上,任何包含函数对象的旧变量都可以调用但是为了方便起见,定义一个函数也为它定义了一个变量名。

这篇关于setTimeout立即调用函数而不是延迟后调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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