Javascript - Run code with delay

By xngo on June 20, 2019

In Javascipt, you can delay the execution of a piece of your code using setTimeout(yourfunction, milliseconds, param1, param2, ...).

  • yourfunction: Required. The function name that will be called.
  • milliseconds: Optional. The number of milliseconds to wait before firing up yourfunction. By default, it is 0.
  • param1, param2, ...: Optional. Parameters values that will be passed to yourfunction.

Please note that setTimeout() doesn't break the flow of execution of your code. It simply set yourfunction aside to be ran later.

Here is an example. The code below will add an input field after 5 seconds.

<!DOCTYPE html>
<html>
    <head>
        <title>Javascript - Run code with delay</title>
 
        <script>
            function myDelayedFunc(){
 
                // Add an input text field.
                document.getElementById("hidden-input").innerHTML = 
                                            '<input type="text" name="firstname">';
            }
 
            function runWithDelay() {
                // Run myDelayedFunc() in 5 seconds.
                setTimeout(myDelayedFunc, 5000);
            }
        </script>
 
    </head>
    <body>
 
        <button onclick="runWithDelay()">Click me to input your firstname in 5 seconds</button>
        <div id="hidden-input"></div>
 
    </body>
</html>

Here is a video showing the code above in action.

Javascript - Example showing running code with delay

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.