How To Use sleep/wait Function In JavaScript?


Share:
Published By: Admin, Published On: Nov 17, 2021, Category: Javascript


Hello Friends,

Now let's see example of how to use sleep and wait function example. We will use how to sleep and wait function in javascript. Here you will learn how to use javascript sleep and wait function. This is a short guide on sleep and wait function. Let's get started with how to sleep and wait function in javascript.

Here i will give you many example how you can sleep and wait function javascript.

Example : 1
<html>
    <head>
        <title>How To Use sleep/wait Function In JavaScript? - MyWebtuts.com</title>
    </head>
    <body>
        <h3>How To Use sleep/wait Function In JavaScript? - MyWebtuts.com</h3>
        <script>
            function s1(milliseconds) {
                return new Promise(resolve => setTimeout(resolve, milliseconds));
            }
            async function a1() {
                document.write('Hello World');
                for (let i = 1; i <=5 ; i++) {        
                    await s1(2000);
                    document.write( i + " " + "Welcome to the MyWebtuts.com" + " " + "</br>");
                }
            }
            a1();
        </script>
    </body>
</html>
Output :
Example : 2
<!DOCTYPE html>
<html>
    <head>
        <title>How To Use sleep/wait Function In JavaScript? - MyWebtuts.com</title>
    </head>
    <body>
        <h3>How To Use sleep/wait Function In JavaScript? - MyWebtuts.com</h3>
        <p>There is a sleep of 4000 milliseconds</p>
        <script>
            let sleep = ms => {
                return new Promise(resolve => setTimeout(resolve, ms));
                };

                document.write("Welcome to the MyWebtuts.com" + "<br>");

                sleep(4000).then(() => {
                document.write("End");
            });
        </script>
    </body>
</html>
Output :

It will help you...

Share: