The following function shows the alert every 5 seconds:
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:
Why is this and how can I loop through the function with a delay while passing arguments?
It’s not working because you are invoking the function when using
You could use the
.bind() method to pass the
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.