Skip to content

JavaScript settimeout with parameters | Code

  • by

The setTimeout() method is used to call a function after a number of milliseconds (specified time). JavaScript settimeout with parameters are optional to pass to the function.

setTimeout(function, milliseconds, param1, param2, ...)
setTimeout(myFunc, 2000, "param1", "param2");

JavaScript settimeout with parameters

Simple example program to pass 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:

JavaScript settimeout with parameters

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);

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

Leave a Reply

Your email address will not be published. Required fields are marked *