Net-informations.com

How to set time delay in JavaScript

JavaScript is a scripting language and scripting languages are always synchronous and single-threaded. While in a specific case, it might be nice to have the whole engine wait for a few seconds, in general it is bad practice. But, it's perfectly reasonable to want to perform an action, wait, and then perform another action in JavaScript. Well, there are different functions and methods that help you to achieve this task in JavaScript.
How to Sleep/Wait/Delay in Code Execution  JavaScript

Javascript setTimeout()

The first and the most common method in implementing a delay in the execution of a JavaScript code is to use the setTimeOut() method.

  1. functionname - The function name for the function to be executed.
  2. milliseconds - The number of milliseconds.
run this source code Try it Yourself

Full Source | JavaScript

Javascript setInterval()

Javascript setTimeout executes only once after the delay whereas setInterval() keeps on calling the callback function after every delay milisecs. Both these methods returns an integer identifier that can be used to clear them before the timer expires. The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

  1. functionname - The function name for the function to be executed.
  2. milliseconds - The number of milliseconds.
run this source code Try it Yourself

Full Source | JavaScript

Output:

Javascript sleep()

JavaScript has evolved significantly. You can use some approaches for simulating the sleep() function in JavaScript. The features such as promises and async/await function in JavaScript helped us to use the sleep() function in an easier way.

Or as a one-liner:

Or

The sleep() function can be used along with the async/await to get the pause between the execution.

example

Output:










net-informations.com (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About