只是出于好奇 - 有人可以向我解释 setTimeout() 的奇怪之处吗?
我所说的奇怪之处是指这两件事:
- 第一个参数中的函数需要被包围 报价,否则延迟设置为 0(一切都执行 即刻)。
- 超时后的所有事情都需要有一个延迟,如下所示 好吧,否则它会在超时结束之前执行。
如果有办法绕过#2,那就太棒了,但现在我只是对此感到好奇。
简短的片段来解释我在说什么:
for (var i=0; i<10; i++) setTimeout("addInput('.')",i*500);
setTimeout('addInput("</br>")',5100);
在上面,除非 addInput('.') 用引号引起来,否则延迟将被忽略并且代码将被执行;另外,除非我在第二行添加超时,否则它将在第一个超时完成之前执行。
By oddities, I mean these two things:
- Functions in the first parameter need to be surrounded by
quotations, or else the delay is set to 0 (Everything is executed
instantly). - Everything after the timeout needs to have a delay after it as
well, or else it is executed prior to the timeout finishing.
If there's a way around #2 - that would be awesome, but right now I'm just curious on this.
Short snippet to explain what I'm talking about:
for (var i=0; i<10; i++) setTimeout("addInput('.')",i*500);
setTimeout('addInput("</br>")',5100);
In the above, unless addInput('.') is surrounded by quotations, the delay is ignored and the code is just executed; also unless I add a timeout to the second line, it will be executed before the first timeout is finished.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
未必。事实上,建议使用直接采用函数指针而不是字符串的重载,以避免解析它的开销:
或其等效项(警告:在 IE 中不起作用):
以下 setTimeout 重载是最常用的一种:
Not necessarily. In fact it is recommended to use the overload which takes directly a function pointer instead of a string to avoid the overhead of parsing it:
or its equivalent (warning: doesn't work in IE):
The following setTimeout overload is the one that is most commonly used:
setTimeout 采用函数引用。这意味着您需要向其传递函数或匿名函数的名称,而不是执行函数的结果。
所以这可行:
但是,这不行:
第二个示例立即执行
fn()
并将该函数的返回值传递给setTimeout()
这通常不是您想要的想要(不会有任何延迟)。如果您需要向函数传递参数,那么您需要将其包装在像这样的容器函数中,因为 setTimeout 将在不带参数的情况下调用您的函数:
setTimeout takes a function reference. That means you need to pass it the name of a function or an anonymous function, not the result of executing a function.
So this works:
But, this does not:
The second example executes
fn()
immediately and passes the return value from that function tosetTimeout()
which is usually not what you want (you get no delay).If you need to pass a parameter to your function, then you need to wrap it in a container function like this because setTimeout will call your function with no parameters:
这是因为您首先调用该函数,然后将返回值发送到
setTimeout
方法。您可以只使用函数名称,或者如果您需要发送参数,请创建一个匿名函数:setTimeout(function() { addInput('.') }, i*500);
setTimeout
方法不会延迟代码,而是将代码放入计时器的回调中。setTimeout
调用后面的代码立即执行。That's because you are calling the function first, then sending the return value to the
setTimeout
method. You can use just the function name, or if you need to send in parameters, make an anonymous function:setTimeout(function() { addInput('.') }, i*500);
The
setTimeout
method doesn't delay the code, it puts the code in the callback of a timer. The code following thesetTimeout
call follows immediately.