From MDN, WindowTimers.setTimeout
allows for the following syntax:
var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);
If you pass setTimeout
a string, it will eval
uate it. This is both slow and dangerous, so DO NOT do it. You are only asking for trouble. Instead, pass a function as the first parameter. For example:
// you can pass an anonymous function
setTimeout(function () { /* do something */ }, 420)
// or, a named function
// note how you don't pass an executed function, e.g., `someAwesomeFunc()`,
// UNLESS `someAwesomeFunc` returns a function
setTimeout(someAwesomeFunc, 9000)
Here's a more comprehensive example. Make sure to look at your console:
/* ~~~ EXAMPLE #0 ~~~ */
// the passed string is evaluated
// DO NOTE DO THIS…EVER!
setTimeout('console.log("hi", new Date())', 1000)
/* ~~~ EXAMPLE #1 ~~~ */
// an anonymous function is passed
// everything is bueno
setTimeout(function () {
console.log('hi! #2', new Date())
}, 2000)
/* ~~~ EXAMPLE #2 ~~~ */
// note how `getHi` *returns* an anonymous function
// that means `typeof getHi(420) === 'function'`
var getHi = function (num) {
return function () {
console.log('hi! #' + num, new Date())
}
}
// as previously stated `getHi(420)` returns a function
// so this works in the same manner as example #2
setTimeout(getHi(420), 4200)
/* ~~~ EXAMPLE #3 ~~~ */
var returnHi = function () { return 'hi!' }
// `returnHi` returns neither function nor code, so a syntax error is thrown
setTimeout(returnHi(), 5000) // <-- doesn't work