DEV Community

Cover image for How can you implement the sleep() function in Javascript?
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

How can you implement the sleep() function in Javascript?

Hello Folks πŸ‘‹

What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer.

Today, I am here again with an amazing topic that you'll love reading. So let's gets started πŸš€


🌟 Introduction

By default, Javascript doesn't come with the sleep() function. To implement sleep timers, setTimeout() function is the closest equivalent to the sleep() function. There, are other few less common ways to implement a sleep function to create a pause after some specified duration of the time.

setTimeout

setTimeout() sets a timer for a function that executes the code once after the time expires. The only code that is inside the setTimeout() function will execute after the given amount of time. Duration is always written in milliseconds(ms). Here's how you write the setTimeout() function.

const printHelloWorld = () => {
  console.log("Hello");
  setTimeout(() => console.log("World"), 500);
};

printHelloWorld(); // "Hello", "World" ("World" logs after 500ms)
Enter fullscreen mode Exit fullscreen mode

Synchronous method

Here, we can use a loop to stop the execution of the function

const sleep = (ms) => {
  const stop = new Date().getTime() + ms;
  while (new Date().getTime() < stop) {}
}

const printHelloWorld = () => {
  console.log("Hello");
    sleep(500)
  console.log("World")
};

printHelloWorld(); // "Hello", "World" ("World" logs after 500ms)
Enter fullscreen mode Exit fullscreen mode

Asynchronous method

A less interfering method to implement the sleep() function using the async and await and a setTimeout() and Promise. Since we are dealing with the Promise the executing function must be async.

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

const printHelloWorld = () => {
  console.log("Hello");
    sleep(500)
  console.log("World")
};

printHelloWorld(); // "Hello", "World" ("World" logs after 500ms)
Enter fullscreen mode Exit fullscreen mode

So, this was it for this article. I hope you learnt something new and enjoy reading. Stay tuned for the next article.

Let's connect on Twitter - @codewithsnowbit

🌏 Let's connect

Top comments (0)