setTimeout 在传递代码时等待,但在传递引用时不等待
为什么像这样传递代码(用“”包围)时:
setTimeout('alert("James Blunt is bad")', 5000);
在显示我们都知道的内容之前是否有 5 秒的暂停以及像这样传递函数引用时:
setTimeout(alert("James Blunt is bad"), 5000);
没有暂停?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你的第二个例子,你没有传递一个函数。
您正在调用
alert
并传递其返回值(并且alert
的返回值不是函数)。函数引用不以
(...)
结尾,或者,在浏览器支持较弱的情况下,将数组中的参数传递给alert,作为 setTimeout 的第三个参数:
If your second example, you are not passing a function.
You are calling
alert
and passing its return value (and the return value ofalert
is not a function).Function references don't end in
(…)
Or, with weaker browser support, pass the arguments to alert in an array as the third argument to setTimeout.:
当您使用代码参数调用 setTimeout 时,必须将其包装在函数中:
否则,当 JavaScript 执行
setTimeout
时,它将立即运行alert
函数,以期alert
将返回一个函数对象,然后将该函数对象放入超时队列中。 (显然,alert
不会返回函数。)When you call setTimeout with a code argument, you have to wrap it in a function:
Otherwise, when JavaScript executes
setTimeout
, it will run thealert
function instantaneously in the hopes that thealert
will return a function object which can then be enqueued onto the timeout queue. (Obviously,alert
will not return a function.)在第二个示例中,您调用
alert
函数,然后调用setTimeout
。这是因为函数的参数是在调用函数之前处理的。 (如果alert有一个返回值,并且您想将该值作为参数传递给另一个函数,那么这正是您想要的行为。)您想要做的是将匿名函数传递给setTimeout,然后让匿名函数调用
alert
,如下所示:In the second example, you are invoking the
alert
function, then callingsetTimeout
. 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 callalert
, like so: