Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I pass a parameter to a setTimeout() callback?
To pass a parameter to setTimeout() callback, you can use additional arguments after the delay parameter or use anonymous functions with closures.
Syntax
setTimeout(functionName, milliseconds, arg1, arg2, arg3...)
The following are the parameters:
- functionName ? The function to be executed.
- milliseconds ? The delay in milliseconds.
- arg1, arg2, arg3 ? Arguments passed to the function.
Method 1: Using Additional Arguments
Pass parameters directly as additional arguments to setTimeout():
<!DOCTYPE html>
<html>
<body>
<button onclick="timeFunction()">Submit</button>
<script>
function displayMessage(name, age) {
alert("Hello " + name + ", you are " + age + " years old!");
}
function timeFunction() {
setTimeout(displayMessage, 3000, "John", 25);
}
</script>
<p>Click the button and wait for 3 seconds.</p>
</body>
</html>
Method 2: Using Anonymous Function
Wrap the function call in an anonymous function to pass parameters:
<!DOCTYPE html>
<html>
<body>
<button onclick="startTimer()">Start Timer</button>
<script>
function showAlert(message, count) {
alert(message + " Count: " + count);
}
function startTimer() {
let counter = 10;
setTimeout(function() {
showAlert("Timer finished!", counter);
}, 2000);
}
</script>
<p>Click to start a 2-second timer.</p>
</body>
</html>
Method 3: Using Arrow Functions
Arrow functions provide a cleaner syntax for passing parameters:
<!DOCTYPE html>
<html>
<body>
<button onclick="executeDelay()">Execute with Delay</button>
<script>
function processData(data, status) {
alert("Processing: " + data + " with status: " + status);
}
function executeDelay() {
setTimeout(() => processData("User Data", "Active"), 1500);
}
</script>
<p>Click to process data after 1.5 seconds.</p>
</body>
</html>
Comparison
| Method | Syntax | Best For |
|---|---|---|
| Additional Arguments | setTimeout(func, delay, arg1, arg2) | Simple parameter passing |
| Anonymous Function | setTimeout(function() { func(args) }, delay) | Complex logic or multiple calls |
| Arrow Function | setTimeout(() => func(args), delay) | Modern, concise syntax |
Conclusion
The additional arguments method is the most direct approach for passing parameters to setTimeout(). Use anonymous or arrow functions when you need more complex parameter handling or multiple function calls.
Advertisements
