Engineer bro!

Sun Feb 20 2022 (1 year ago)

Engineer by mistake!

I am a software engineer by passion

Building a sleep function for JavaScript

The aim of building a sleep function is to allow the program to wait for a specified amount of time before executing the next line. The sleep function has many use cases, as you want to execute another service if the previous service takes more time, etc.

Table of contents

How to build sleep() function?

JavaScript always provides a way to wait at some line number before moving on to the next line using async/await. We'll also use the same concept.

Think what await does.

Consider the below code

async function test(){
    console.log("Before await");
    await someService(..);
    console.log("After await");

If you are familiar with async/await, then you might have guessed that the above code will first log Before await. Then it'll wait for the promise returned by someService to resolve/reject. Then it'll log After await.

So, await wait for the promise to either resolve or reject.

Why not we can use this concept to build a sleep function, which will return a promise and resolve after specified amount of time.

Let's build it

// ms => milliseconds
function sleep(ms) {
  // create and return a Promise
  return new Promise((resolve) => {
    // resolve the Promise after  specified amount of time(ms)
    setTimeout(resolve, ms);

async function test() {
  console.log("Before sleep() -> ", new Date().toLocaleTimeString());
  await sleep(1000); // wait for resolve to be called.
  console.log("After sleep() -> ", new Date().toLocaleTimeString());


// output
Before sleep() ->  7:57:34 pm
After sleep() ->  7:57:35 pm

Let's make the sleep smaller

You can see, currently sleep function consists of 5 lines, we can reduce the number of lines.

3 Line of code

const sleep = (ms) => {
  return new Promise((resolve) => setTimeout(resolve, ms));

4 Single line of code

const sleep = (ms) => new Promise((res) => setTimeout(res, ms));


JavaScriptNodeJsSoftware Engineering

© 2021 dsabyte. All rights reserved