How to make functions sleep in JavaScript

by Sai gowtham1min read
How to make functions sleep in JavaScript

In this tutorial, we are going to learn how to make javascript functions sleep or delay for a particular amount of time. We are taking the help of promise constructor to make the functions sleep.

function sleep(time){
      return new Promise((resolve)=>setTimeout(resolve,time)

Once a promise is resolved chain it with then method and run your code as we did in below code.

 //do something after 2000 milliseconds

async or await

async function add(n1,n2){
   await sleep(2222);

Hope you enjoyed….