setInterval
or setTimeout
You should pass a reference to a function as the first argument for setTimeout
or setInterval
. This reference may be in the form of:
An anonymous function
setTimeout(function(){/* Look mah! No name! */},2000);
A name of an existing function
function foo(){...}
setTimeout(foo, 2000);
A variable that points to an existing function
var foo = function(){...};
setTimeout(foo, 2000);
Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.
To call a function and pass parameters, you can call the function inside the callback assigned to the timer:
setTimeout(function(){
foo(arg1, arg2, ...argN);
}, 1000);
There is another method to pass in arguments into the handler, however it's not cross-browser compatible.
setTimeout(foo, 2000, arg1, arg2, ...argN);
By default, the context of the callback (the value of this
inside the function called by the timer) when executed is the global object window
. Should you want to change it, use bind
.
setTimeout(function(){
this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);
Although it's possible, you should not pass a string to setTimeout
or setInterval
. Passing a string makes setTimeout()
or setInterval()
use a functionality similar to eval()
that executes strings as scripts, making arbitrary and potentially harmful script execution possible.