PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Blocks

    Design blocks for your website

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

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

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)

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)

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)

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

Comments (0)

loading comments