Wait 5 Seconds Before Executing Next Line
This article will illustrate the procedure to execute the next line after waiting for 5 seconds.
How to Wait 5 Seconds Before Executing the Next Line?
To wait 5 seconds before executing the next line, use the following ways:
Method 1: Wait 5 Seconds Before Executing the Next Line Using the setTimeout() Method
Use the “setTimeout()” method for waiting 5 seconds and then execute the next line of code. Using this method, a timer is set, and a function or piece of code is executed when it runs out. More specifically, the time is set in milliseconds.
Use the following syntax for utilizing the setTimeout() method:
In the above syntax:
- “function” is the defined function that will be called after the specified time.
- “time” is the duration for waiting to execute the code. This time duration will be in milliseconds.
Print the string “Welcome To Linuxhint” on the console using the “console.log()” method:
Call the “setTimeout()” method by passing the time in milliseconds and a function that will be invoked after the specified period to print the string on the console:
Here, 5000ms refers to the 5s.
As you can see in the output, the second string, “The best platform to learn skills”, is printed on the console after 5 seconds:
Method 2: Wait 5 Seconds Before Executing the Next Line Using the User-Defined sleep() Function
Define an asynchronous function using the “async” keyword called “executeLine()”. Invoke the “sleep()” function by passing the time in milliseconds:
Finally, call the “executeLine()” function:
As you can see in the output, after executing the code, every line pause for 5 seconds before printing on the console: