How do I add a delay in JavaScript?
Rashid D
rashid d profile pic

To add a delay in JavaScript, you can use various techniques such as setTimeout, setInterval, Promises, or async/await. Here's a step-by-step guide on how to achieve this using the setTimeout method: 1. Determine the duration of the delay:

1
2
3

   const delayInMilliseconds = 2000; // 2 seconds
   

Replace2000 with the desired delay duration in milliseconds. For example, to add a 2-second delay, set it to 2000. 2. Use the setTimeout method: The setTimeout method allows you to execute a function or code after a specified delay.

1
2
3
4
5

   setTimeout(() => {
     // Code to execute after the delay
   }, delayInMilliseconds);
   

In this example, the arrow function() => {} represents the code to be executed after the delay. You can replace it with any code or function you want to execute. 3. Perform the desired actions after the delay: Place the code or function inside the setTimeout callback to execute it after the specified delay.

1
2
3
4
5
6

   setTimeout(() => {
     // Code to execute after the delay
     console.log('Delayed code executed');
   }, delayInMilliseconds);
   

In this example, the delayed code logs a message to the console. 4. Use setTimeout in asynchronous code: If you're working with asynchronous code, such as Promises or async/await, you can wrap setTimeout inside a Promise to add a delay.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

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

   async function asyncCode() {
     // Code before the delay
     console.log('Async code before delay');
     
     await delay(delayInMilliseconds);
     
     // Code after the delay
     console.log('Async code after delay');
   }

   asyncCode();
   

In this example, thedelay() function returns a Promise that resolves after the specified delay. TheasyncCode() function usesawait to pause execution until the delay is complete. This allows you to structure your asynchronous code to wait for the delay before continuing. By following these steps, you can add a delay in JavaScript using the setTimeout method. Adjust the code as needed to suit your specific use case and incorporate it into your application logic.