How to add one second delay in JavaScript

How to add one second delay in JavaScript:

Delay methods are used to add delay in execution of functions. In JavaScript, we can add delay by using the setTimeout method. This method takes one function as the first parameter and delay time as the second parameter.

We can also wrap it with a Promise and resolve it after a specific time. In an async function, we can await for the result of this Promise and that will pause the execution of the code.

In this post, I will show you both of these methods with examples.

Method 1: Using setTimeout:

console.log('T1: ', new Date());

setTimeout(function(){
    console.log('T2: ', new Date());
}, 1000);

Here, T1 log is printed immediately once we run the code. T2 is printed after 1 second1. The timeout or delay is provided in milliseconds in setTimeout.

If you run this program, it will print output as like below:

T1:  2020-08-31T13:12:57.184Z
T2:  2020-08-31T13:12:58.187Z

We can also pass one arrow function to setTimeout:

console.log('T1: ', new Date());

setTimeout(() =>{
    console.log('T2: ', new Date());
},13000);

Method 2: Using a Promise:

We can also create a new function that returns a Promise and that is completed after 1 seconds. Below program does that:

function delay(d) {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(1);
      }, d);
    });
}

console.log('T1: ', new Date());

delay(1000).then(() => console.log('T2: ', new Date()));

delay function takes the milliseconds value as the argument. It returns one Promise. This is completed after d milliseconds. So, the T2 log will print after one second of delay.

Using arrow function:

We can write the delay function using an arrow function:

const delay = d => new Promise(resolve => setTimeout(() => resolve(1), d));

console.log('T1: ', new Date());

delay(1000).then(() => console.log('T2: ', new Date()));

Using with async-await:

For async functions, we can use await with this method.

const delay = d => new Promise(resolve => setTimeout(() => resolve(1), d));

const runDelay = async () => {
    console.log('T1: ', new Date());
    await delay(1000);
    console.log('T1: ', new Date());
}


runDelay();

runDelay is an async method. Using await, we can pause the execution.

It will give similar output:

T1:  2020-08-31T13:30:59.166Z
T1:  2020-08-31T13:31:00.174Z

You might also like: