The setTimeout()
method is used to call a function after a number of milliseconds (specified time). JavaScript settimeout with parameters is optional to pass to the function.
setTimeout(function, milliseconds, param1, param2, ...)
setTimeout(myFunc, 2000, "param1", "param2");
JavaScript settimeout with parameters
A simple example program to pass a parameter to a setTimeout() function. Where the greet()
function is passed to the setTimeout()
and it called after 3000 milliseconds (3 seconds).
<!DOCTYPE html>
<html>
<body>
<script>
function greet() {
console.log('Hello world after 3000ms');
}
// passing parameter
setTimeout(greet, 3000);
console.log('This message is shown first');
</script>
</body>
</html>
Output:
Using additional parameters
<script>
function greet(a, b) {
console.log(a);
console.log(b);
}
setTimeout(greet, 3000, 'Hello', 'world');
console.log('This message is shown first');
</script>
Output:
This message is shown first Hello world
Use an anonymous function
setTimeout(function() {myFunc("param1", "param2")}, 2000);
function myFunction(param1, param2) {
// Your code here
console.log(param1, param2);
}
// Using an anonymous function to pass parameters
setTimeout(function() {
myFunction('Hello', 'World');
}, 1000); // 1000 milliseconds (1 second) delay
In this example, an anonymous function is used to wrap the call to myFunction
with the desired parameters. The setTimeout
function then executes this anonymous function after the specified delay.
Alternatively, you can use the bind
method to create a new function with specified parameters:
function myFunction(param1, param2) {
// Your code here
console.log(param1, param2);
}
// Using bind to pass parameters
var delayedFunction = myFunction.bind(null, 'Hello', 'World');
setTimeout(delayedFunction, 1000); // 1000 milliseconds (1 second) delay
In this example, the bind
method is used to create a new function (delayedFunction
) that, when called, will invoke myFunction
with the specified parameters. This new function is then passed to setTimeout
.
Do comment if you have any doubts or suggestions on this JS set timeout topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version