admin管理员组文章数量:1429513
The following function shows the alert every 5 seconds:
function foo() {
bar="foo";
alert (bar);
setTimeout(foo, 5000);
}
foo();
However, when I add arguments to the function and call from setTimeout
, it no longer waits 5 seconds, it just alerts endlessly without any delay:
function foo(bar) {
bar="foo";
alert (bar);
setTimeout(foo(bar), 5000);
}
foo();
Why is this and how can I loop through the function with a delay while passing arguments?
The following function shows the alert every 5 seconds:
function foo() {
bar="foo";
alert (bar);
setTimeout(foo, 5000);
}
foo();
However, when I add arguments to the function and call from setTimeout
, it no longer waits 5 seconds, it just alerts endlessly without any delay:
function foo(bar) {
bar="foo";
alert (bar);
setTimeout(foo(bar), 5000);
}
foo();
Why is this and how can I loop through the function with a delay while passing arguments?
Share Improve this question edited Dec 20, 2015 at 2:10 Josh Crozier 242k56 gold badges400 silver badges313 bronze badges asked Dec 19, 2015 at 22:17 dlofrodlohdlofrodloh 1,7443 gold badges25 silver badges48 bronze badges 2- Possible duplicate of How can I pass a parameter to a setTimeout() callback? – tckmn Commented Dec 19, 2015 at 22:19
-
1
foo(bar)
isn't a function. You've invoked a function and by definition, that invoked function returns something whether the return statement is there or not. – Quy Commented Dec 19, 2015 at 22:20
3 Answers
Reset to default 7JavaScript thinks you want to call foo(bar)
immediately then pass its result into setTimeout()
, which isn't what you mean. Instead, you should create an anonymous function with your call inside it, like this:
function foo(bar) {
bar = "foo";
alert(bar);
setTimeout(function() {
foo(bar)
}, 5000);
}
It's not working because you are invoking the function when using setTimeout(foo(bar), 5000)
.
You could use the .bind()
method to pass the bar
variable:
setTimeout(foo.bind(this, bar), 5000);
The first parameter is the value of this
to be passed to the function. It can be null
if you don't need it. The following parameters are the arguments that are passed. In this case, bar
is the first argument.
You could use the parameters arguments (after the 2nd argument):
setTimeout(foo, 5000, bar);
Basically, any arguments after the 2nd argument are passed down to the function supplied in the first argument.
本文标签: How to call javascript function with arguments with setTimeoutStack Overflow
版权声明:本文标题:How to call javascript function with arguments with setTimeout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745515725a2661527.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论