Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 31, 2020 10:29 am GMT

Sleep function in javaScript

JavaScript provides setTimeout() and setInterval() methods to delay execution of script. But, it doesn't provide any way to sleep execution at a single line. Let's build our custom sleep method.

TOC

  1. Prerequisites
  2. idea
  3. sleep API
  4. uses
  5. live interactive demo

Prerequisites

I am assuming that you know the above prerequisites.

Idea is to use a promise to wait for a number of milliseconds. We know, we can delay the execution of certain script using await. Using await we can run the next script after the promise is resolved or rejected.

Let's build our sleep API

function sleep(ms){  return new Promise((resolve)=>{    setTimeout(()=>resolve(),ms);  })}
Enter fullscreen mode Exit fullscreen mode

The above sleep API will wait for some milliseconds, then it resolves the promise.

Uses

make sure to call this API inside the async function

async function test(){    // wait for 3 seconds    console.log("Waiting...");    await sleep(3000);     console.log("The wait is over");}
Enter fullscreen mode Exit fullscreen mode

Live demo

See the Pen oNzpMZN by Rahul kumar
(@ats1999) on CodePen.


Original Link: https://dev.to/ats1999/sleep-function-in-javascript-785

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To