setTimeout()
is a function that allows you to execute a specified function or evaluate an expression after a specified number of milliseconds. In this article, you’ll discover four methods for passing parameters to setTimeout().
Using an anonymous function
Wrap the function call in an anonymous function. An anonymous function is a function that is defined without a name.
Syntax of an anonymous function
function() {
...
}
setTimeout()
with an anonymous function.
function showName(name) {
console.log(`Hello, ${name}!`);
}
const name = "Matej";
setTimeout(function() {
showName(name);
}, 2000);
The recommended way to capture the value of a variable at the time setTimeout
is called, is to use an immediate-invoked function expression (IIFE).
function showName(name) {
console.log(`Hello, ${name}!`);
}
let name = "Matej";
setTimeout(function(uname) {
return function() {
showName(uname);
};
}(name), 2000);
name = "Adam";
This snippet demonstrates an immediate-invoked function expression (IIFE) that captures the current value of the name
variable (Matej
) and passes it to the inner function, which setTimeout
will call after 2 seconds.
If you don’t use the IIFE approach, you will see “Adam
” as the output instead of “Matej
“. The reason for this is that the value of the variable name
is changed to “Adam
” before the setTimeout
callback is executed.
Using function.bind()
The bind
method is used to make a new version of a function (showName
) that is ready to use with specific settings. When you have a function that takes parameters, such as showName(name)
, you can use bind
to create a new function where some of these parameters are already specified.
Example
function showName(name) {
console.log(`Hello, ${name}!`);
}
const name = "Matej";
setTimeout(showName.bind(null, name), 2000);
Using arrow functions
You can also use arrow functions for the anonymous function approach.
function showName(name) {
console.log(`Hello, ${name}!`);
}
const name = "Matej";
setTimeout(() => {
showName(name);
}, 2000);
Using the IIFE approach, you ensure that the value of name
is captured at the moment setTimeout
is called, and any subsequent changes to the name
variable will not affect the captured value.
function showName(name) {
console.log(`Hello, ${name}!`);
}
let name = "Matej";
setTimeout(((uname) => {
showName(uname);
})(name), 2000);
name = "Adam";
Passing additional arguments
You can pass additional arguments to the function inside setTimeout()
by adding them after the milliseconds argument.
function showName(name) {
console.log(`Hello, ${name}!`);
}
const name = "Matej";
setTimeout(showName, 2000, name);