How to make your Javascript Functions sleep?

We may encounter some scenarios where we have to pause the execution of a function for some fixed amount of time.

Many programming languages already have a built-in sleep method available.
To halt a program for 2 seconds, we've got the following implementations:

LanguageExecution
C or PHPsleep(2)
JavaThread.sleep(2000)
Pythontime.sleep(2)
Gotime.Sleep(2 * time.Second)

Since Javascript doesn't support this functionality by itself, we've to create it ourselves. So the first approach that comes to mind might be to use setTimeout API. In the example below I'm trying to print numbers, and 2 & 3 should get printed 5 seconds after 1.

function sleep(ms){
  setTimeout(()=>{
    console.log("dealying...")
  },ms);
}

function printNumbers(){
  console.log(1);
  sleep(5000); // It won't cause the execution of printNumbers to pause here.
  console.log(2);
  console.log(3);
}

printNumbers();

Here, we've used sleep, in the printNumbers function, but it won't cause the execution to pause, instead 2 will get printed immediately after 1, and sleep function will be of no use.
This is because setTimeout is asynchronous and so moved out of the call stack and the remaining program's execution keeps going on. Once 5 seconds have elapsed and the call stack is empty, the callback passed in setTimeout, will get executed. So this approach clearly didn't solve our approach.

So, we can think of using Promise to solve our problem. executor function passed to a Promise Constructor provides a resolve function as an argument. If we can delay resolving the promise, we might be able to create the sleep functionality.

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

function printNumbers(){
  console.log(1);
  sleep(5000).then(()=>{
    console.log(2);
    console.log(3);
  });
}

As we can see in the example above, whatever we need to delay we can put that piece of code in the callback function passed to then.

We can make the above code cleaner using the async-await syntax.

async function printNumbers2(){
  console.log(1);
  await sleep(5000);
  console.log(2);
  console.log(3);
}

Here we can just write our code normally as we do for any asynchronous piece of code. It's just that in order to use the sleep functionality we can only use it within a function prefixed with async and the sleep should also be prefixed with the await keyword inorder to have the pause/sleep effect.

References

  1. Flavio Copes | How to make your JavaScript functions sleep
  2. educative.io | Aaron Xie | What is the Javascript alternative to the sleep function?
  3. Stackoverflow
  4. Youtube | Sleep with Async / Await