Back to JavaScript
2025-12-055 min read

JavaScript Program to Pass Parameter to a setTimeout() Function

Learn JavaScript Program to Pass Parameter to a setTimeout() Function step by step with clear examples and exercises.

Why This Matters

Understanding how to pass parameters to the setTimeout() function is crucial for asynchronous programming in JavaScript, enabling you to create flexible and reusable code. This lesson will walk you through the core concept, worked example, common mistakes, practice questions, and frequently asked questions related to this topic. Mastering parameter passing with setTimeout() will help you tackle real-world programming challenges and avoid common pitfalls.

Prerequisites

Before diving into the core concept, it's essential that you have a good understanding of the following JavaScript topics:

  1. Variables and data types: Learn about declaring variables using let and const, as well as basic data types like numbers, strings, booleans, arrays, and objects.
  2. Functions: Understand how to define and call functions in JavaScript, including function declarations, function expressions, and arrow functions.
  3. Callback functions: Learn about callback functions and how they are used to pass functions as arguments to other functions.
  4. Asynchronous programming concepts: Familiarize yourself with the basics of asynchronous programming, including event loops, promises, and async/await.

Core Concept

The setTimeout() function takes two arguments: a function to be executed and the number of milliseconds to wait before executing the function. However, it doesn't support passing parameters directly. To pass parameters, you can define an anonymous function that includes the desired parameters and then call this function as the argument for setTimeout().

Here's a simple example:

function greet(name) {
console.log(`Hello, ${name}!`);
}

// Define an anonymous function with the parameter 'message'
const greetWithMessage = function(message) => () => greet(message);

// Pass the message parameter to the setTimeout function
setTimeout(greetWithMessage('World'), 3000);
console.log('This message is shown first');

In this example, we have a greet() function that takes a name as an argument and logs a greeting. We then define another anonymous arrow function called greetWithMessage, which accepts a message parameter and returns an inner function that calls the greet() function with the provided message. Finally, we pass this inner function to setTimeout().

Anonymous Functions

Anonymous functions are functions that are not given a name. They can be defined using function expressions or arrow functions. In the example above, we define an anonymous function using an arrow function.

// Function Expression
const greetWithMessage = function(message) => {
return () => greet(message);
};

// Arrow Function
const greetWithMessageArrow = (message) => () => greet(message);

Inner Functions

Inner functions are functions defined within another function. In the example above, we define an inner function inside greetWithMessage. The inner function is returned by greetWithMessage and can be called as the argument for setTimeout().

Worked Example

Let's build a simple program that counts down from 10 using setTimeout() and passes the remaining time as a parameter:

function countdown(remainingTime, callback) {
if (remainingTime <= 0) {
console.log('Countdown finished!');
callback(); // Call the provided callback function when the countdown finishes
return;
}

console.log(`Remaining time: ${remainingTime}`);
remainingTime--;
setTimeout(function() { countdown(remainingTime, callback); }, 1000);
}

const myCallback = function() {
console.log('Countdown complete! Let the party begin!');
};

countdown(10, myCallback);

In this example, we have a countdown() function that takes two arguments: the remaining time and a callback function to be executed when the countdown finishes. Inside the function, we check if the remaining time is less than or equal to zero. If so, we call the provided callback function and return. Otherwise, we log the current remaining time, decrement it by one, and call setTimeout() to continue the countdown after one second.

Callback Functions

Callback functions are functions that are passed as arguments to other functions and are executed inside those functions. In this example, we pass a callback function called myCallback() to the countdown() function. When the countdown finishes, myCallback() is called.

Common Mistakes

  1. Not returning the inner function: In the example above, we return the inner function from greetWithMessage. If you forget to do this, the inner function will not be executed when passed to setTimeout().
  1. Incorrect parameter passing: Ensure that the parameters you pass to your anonymous function are defined correctly and in the correct order.
  1. Not handling edge cases: Be aware of edge cases, such as when the remaining time is zero or less than zero, and handle them appropriately in your countdown() function.
  1. Forgetting to call the callback function: In the countdown() example, remember to call the provided callback function when the countdown finishes.

Edge Cases

Edge cases are situations that occur infrequently but can still cause problems in your code if not handled correctly. For example, when the remaining time is zero or less than zero in the countdown() function, you should log an error message instead of continuing with a negative count.

Practice Questions

  1. Write a JavaScript program that logs the numbers from 1 to 10 using setTimeout(). Pass the current number as a parameter to the inner function.
function count(number, callback) {
if (number > 10) return;

console.log(number);
number++;
setTimeout(function() { count(number, callback); }, 1000);
}

const myCallback = function() {
console.log('Count complete!');
};

count(1, myCallback);
  1. Modify the countdown() function to log a different message when the countdown reaches zero (e.g., "Blast off!").
function countdown(remainingTime, callback) {
if (remainingTime <= 0) {
console.log('Countdown finished! Blast off!');
callback(); // Call the provided callback function when the countdown finishes
return;
}

console.log(`Remaining time: ${remainingTime}`);
remainingTime--;
setTimeout(function() { countdown(remainingTime, callback); }, 1000);
}

FAQ

How can I pass multiple parameters to setTimeout()?

You can create an anonymous function that accepts multiple parameters and returns another inner function with those parameters. Then, call this inner function as the argument for setTimeout().

function greet(name, message) {
console.log(`Hello, ${name}! ${message}`);
}

const greetWithParams = function(name, message) => () => greet(name, message);

setTimeout(greetWithParams('World', 'Goodbye!'), 3000);

Why does my code not execute the inner function when passed to setTimeout()?

Ensure that you are returning the inner function from the outer anonymous function before passing it to setTimeout(). If you forget to do this, the inner function will not be executed.

How can I pass a variable defined outside of the anonymous function as a parameter to the inner function?

You can declare the variable with let or const and assign it a value before defining the anonymous function. Then, you can access and use this variable inside the anonymous function.

let message = 'Hello World!';

const greetWithMessage = () => () => console.log(message);

setTimeout(greetWithMessage(), 3000);
JavaScript Program to Pass Parameter to a setTimeout() Function | JavaScript | XQA Learn