How to call javascript function with arguments with setTimeout

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?


solution

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.