setTimeout 在传递代码时等待,但在传递引用时不等待

发布于 2024-12-28 01:35:17 字数 325 浏览 0 评论 0原文

为什么像这样传递代码(用“”包围)时:

setTimeout('alert("James Blunt is bad")', 5000);

在显示我们都知道的内容之前是否有 5 秒的暂停以及像这样传递函数引用时:

setTimeout(alert("James Blunt is bad"), 5000);

没有暂停?

http://jsfiddle.net/eBcpc/

Why when passing the code (surrounded by '') like so:

setTimeout('alert("James Blunt is bad")', 5000);

Is there the 5 second pause before showing what we all know and when passing function reference like so:

setTimeout(alert("James Blunt is bad"), 5000);

There is no pause?

http://jsfiddle.net/eBcpc/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一身仙ぐ女味 2025-01-04 01:35:17

如果你的第二个例子,你没有传递一个函数。

您正在调用 alert 并传递其返回值(并且alert 的返回值不是函数)。

函数引用不以 (...) 结尾

setTimeout(function () { alert("Hello, world"); }, 5000);

,或者,在浏览器支持较弱的情况下,将数组中的参数传递给alert,作为 setTimeout 的第三个参数:

setTimeout(alert, 5000, ["Hello, world"]);

If your second example, you are not passing a function.

You are calling alert and passing its return value (and the return value of alert is not a function).

Function references don't end in (…)

setTimeout(function () { alert("Hello, world"); }, 5000);

Or, with weaker browser support, pass the arguments to alert in an array as the third argument to setTimeout.:

setTimeout(alert, 5000, ["Hello, world"]);
☆獨立☆ 2025-01-04 01:35:17

当您使用代码参数调用 setTimeout 时,必须将其包装在函数中:

setTimeout(function () { alert("James Blunt is bad"); }, 5000);

否则,当 JavaScript 执行 setTimeout 时,它将立即运行 alert 函数,以期alert 将返回一个函数对象,然后将该函数对象放入超时队列中。 (显然,alert 不会返回函数。)

When you call setTimeout with a code argument, you have to wrap it in a function:

setTimeout(function () { alert("James Blunt is bad"); }, 5000);

Otherwise, when JavaScript executes setTimeout, it will run the alert function instantaneously in the hopes that the alert will return a function object which can then be enqueued onto the timeout queue. (Obviously, alert will not return a function.)

屌丝范 2025-01-04 01:35:17

在第二个示例中,您调用 alert 函数,然后调用 setTimeout。这是因为函数的参数是在调用函数之前处理的。 (如果alert有一个返回值,并且您想将该值作为参数传递给另一个函数,那么这正是您想要的行为。)

您想要做的是将匿名函数传递给setTimeout,然后让匿名函数调用 alert,如下所示:

setTimeout(function() {
        alert("James Blunt is bad");
    }, 5000);

In the second example, you are invoking the alert function, then calling setTimeout. This is because the arguments to a function are processed before the function is called. (If alert had a return value and you wanted to pass that value as an argument to another function, then this is exactly the behavior you would want.)

What you want to do is pass an anonymous function to setTimeout, then have that anonymous function call alert, like so:

setTimeout(function() {
        alert("James Blunt is bad");
    }, 5000);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文