How to Use Sleep in Javascript

Hello devs, today I'll show how to use sleep in JavaScript code. This will be much efficient when you want to send request to your server side. So, let's see how we can sleep our code for a certain amount of time.

Example 1

We'll use the setTimeout() function under a promise-based request, which will cause our script to wait for 2second after each execution.

Let's see the below source code for more clarification.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>JS Sleep</title>
    <link rel="stylesheet" href="">
</head>
<body>
    <script>

const list = [1, 2, 3, 4]
const task = async () => {
  for (const item of list) {
    await new Promise(r => setTimeout(r, 2000));
    console.log('Hello, Devs');
  }
}

task();

    </script>
</body>
</html>

Which will produce the below result 

 

But hold on a second, this 4 in an image not come at once. This is iterated after 2 seconds each which cause total 8 sec to complete our loop.

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading.