The setTimeout() function is a method in JavaScript that allows you to execute a piece of code after a specified amount of time has elapsed. It takes two arguments: the first argument is the function that needs to be executed, and the second argument is the time in milliseconds after which the function should be executed.
In this article, we will discuss how to pass a parameter to the setTimeout()
function in JavaScript.
setTimeout(function, delay);
Where function
is the function or code that you want to execute after a specified amount of time (in milliseconds) and delay
is the amount of time to wait before executing the function.
To pass a parameter to the function that is being executed by the setTimeout()
function, we can create an anonymous function that calls the desired function with the parameter and pass it to the setTimeout()
function instead. Here is an example:
let parameter = "example";
setTimeout(function() {
myFunction(parameter);
}, 1000);
function myFunction(param) {
console.log(param);
}
In this example, we first declare a variable parameter
with the value “example”. We then pass an anonymous function to the setTimeout()
function, which calls the myFunction()
function and passes it the parameter
variable as an argument. The myFunction()
function takes one argument param
and print it in the console. The setTimeout()
function waits for 1 second before executing the anonymous function.
We can also use arrow function and pass the parameter directly like this:
let parameter = "example";
setTimeout(() => myFunction(parameter), 1000);
function myFunction(param) {
console.log(param);
}
This is a shorter version of the same code that pass the parameter
to myFunction
and it will run after 1 sec.
Passing a parameter to the setTimeout()
function in JavaScript can be done by wrapping the desired function in an anonymous function and passing the parameter as an argument. This is a powerful feature that allows you to create more advanced and dynamic scripts, and it’s widely used in web development.
Thanks for reading. Happy coding!