DEV Community

Adithyan A
Adithyan A

Posted on

How to make a JS function wait after executing a specific line of code

Basis Idea

The basic idea is that we have a function and for some reason we need to make the JS program wait after executing some part of the function

Application

Let's assume that we have a function to find the sum of two numbers and we need to make the program wait 3 second before printing the result

function sumOfTwoNumbers() {
  const num1 = 100;
  const num2 = 22;
  const sum = num1 + num2;
  // Wait for 3sec before executing
  console.log("The sum is:", sum);
}
Enter fullscreen mode Exit fullscreen mode

Step-1

Create a new function sleep which returns a promise.
This function will make the program wait for the specified milliseconds

Remember 1 second = 1000 millisecond

function sleep(timeInMilliSecond) {
  return new Promise((resolve) => setTimeout(resolve, timeInMilliSecond));
}
Enter fullscreen mode Exit fullscreen mode

Step-2

Convert the function (In which we need to make the program wait) to a Asynchronous function, In our case sumOfTwoNumbers()

// Put keyword async before function keyword to convert function to a asynchronous function
async function sumOfTwoNumbers() {
  const num1 = 100;
  const num2 = 22;
  const sum = num1 + num2;
  // Wait for 3sec before executing
  console.log("The sum is:", sum);
}
Enter fullscreen mode Exit fullscreen mode

Step-3

Make the program wait for specified amount of milliseconds

async function sumOfTwoNumbers() {
  const num1 = 100;
  const num2 = 22;
  const sum = num1 + num2;
  // Add the below line to make the program wait for 3seconds
  await sleep(3000);
  console.log("The sum is:", sum);
Enter fullscreen mode Exit fullscreen mode

Result

Now the program will wait for 3 seconds before it prints the output

Top comments (0)