Signup/Sign In
PUBLISHED ON: FEBRUARY 23, 2023

JavaScript Program to Pass Parameter to a setTimeout() Function

Want to improve your JavaScript abilities? Looking for a JavaScript method to execute a function with a delay? The setTimeout() function is one of the most common ways to execute code with a delay in JavaScript. '

In this article, we will examine how to pass parameters to the setTimeout() function and optimize your code by utilizing this feature.

We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

Passing Parameter to setTimeout

In the program given below, the about() function is passed to the setTimeout(). The about() function then gets called after 3000 milliseconds [ 3 seconds ].

Hence, the program displays the text passed by the about function only once after 3 seconds.

Program to Pass Parameter to a setTimeout() Function

// JavaScript Program to pass a parameter to a setTimeout() function

function about() {
    console.log('JavaScript is the worlds most popular programming language. JavaScript is the programming language of the Web.');
}

// passing parameter
setTimeout(about, 3000);
console.log(" This particular message is shown first ");

This particular message is shown first
JavaScript is the world's most popular programming language. JavaScript is the programming language of the Web.

Passing Parameter to Function

In the program given below, additional parameters x and y are required in the about() function.

When calling the setTimeout() function, we pass on the two values passed as the parameter into the about() function.

// program to pass parameter to function in setTimeout()
function about(x, y) {
    console.log(x);
    console.log(y);
}

// passing the parameters
setTimeout(about, 3000, 'JavaScript is the worlds most popular programming language.', 'JavaScript is the programming language of the Web.');
console.log('This message is shown first');


This message is shown first
JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.

Conclusion

The setTimeout() function takes two arguments: a function to execute and a time interval in milliseconds. However, it is also possible to pass parameters to the function being executed using the setTimeout() function.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.