This post will discuss how to delay execution of some code or function in JavaScript. In other words, add a time delay in JavaScript.

There are several ways to add a time delay in JavaScript, depending on how long we want to delay the execution of some code or function. Here are some of the common functions:

1. Using setTimeout() function

One way is to use the setTimeout() function, which is a built-in function that takes two parameters: a callback function and a delay time in milliseconds. The callback function can be either a named function or an anonymous function, and will be executed after the delay time has passed. For example, if we want to log "Hello" message to the console after 2 seconds and "World" message after 3 seconds, we can do this:

Download  Run Code

2. Using async/await syntax

This syntax allows us to write asynchronous code in a synchronous manner, by using the await keyword to pause the execution of a function until a promise is resolved. A promise is an object that represents the completion or failure of an asynchronous operation. We can create a custom function that returns a promise that resolves after a certain time, and then use the await keyword to pause the execution until the promise is fulfilled. For example, if we want to log a message to the console after 2 seconds, we can do this:

Download  Run Code

3. Using Promise

Another way is to use the Promise constructor and the then() function, which are also features of ES6 that allow us to work with asynchronous operations. We can create a new promise that resolves after a certain time, and then use the then() function to execute a callback function when the promise is resolved. For example, if we want to log a message to the console after 2 seconds, we can do this:

Download  Run Code

That’s all about delaying execution of some code or function in JavaScript.