最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to call javascript function with arguments with setTimeout - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 7

JavaScript 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.

发布评论

评论列表(0)

  1. 暂无评论