JS Tip of the Day: setTimeout Callback Arguments

setTimeout Callback Arguments
Level: Beginner

The setTimeout function lets you delay the call of a callback function by a specified number of milliseconds.

function afterAWhile () {
    console.log('after a while, crocodile');
}

setTimeout(afterAWhile, 2000);
console.log('later, alligator'); 
/* logs:
later alligator
(waits 2 seconds)
after a while, crocodile
*/

As with most callbacks, since you are not in direct control of calling the callback function, you do not necessarily decide how the function is called or with what arguments. However, in the case of setTimeout (and setInterval), it does let you specify the arguments its callback gets called with. Any arguments you provide to after the millisecond (delay) argument will be automatically forwarded to the callback when it’s ultimately called.

function afterAWhile (whom) {
    console.log('after a while, ' + whom);
}

setTimeout(afterAWhile, 2000, 'crocodile');
console.log('later, alligator'); 
/* logs:
later alligator
(waits 2 seconds)
after a while, crocodile
*/

More info: