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 upyourfunction
. By default, it is 0.param1, param2, ...
: Optional. Parameters values that will be passed toyourfunction
.
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.