Sleep Function in JavaScript

Sometimes we want to do something after some time, like, for example, we may want to execute some part of a script, after 5 seconds.

In many programming languages, we do this with sleep() function.

JavaScript doesn’t have its own sleep() function, but we can achieve similar behavior with some alternatives, or we can even make our own sleep() function.

<script>
    var millisecondsToWait = 3000;

    async function doSomething() {
        await new Promise(x => setTimeout(x, millisecondsToWait));
        console.log('something');
    }

    doSomething();
</script>

This, however, will work only with asynchronous functions.

Alternatively, we can also use setTimeout().

<script>
    setTimeout(function() {
        console.log('something');
    }, 3000)
</script>

Custom sleep() function in JavaScript

<script>
    function sleep(ms) {
        return new Promise(x => setTimeout(x, ms));
    }

    // Example:

    async function test() {
        console.log('Hello')
        
        await sleep(2000);

        console.log(' World!');
    }

    test();
</script>