How To Make Javascript Wait 5 Seconds

When building a web application, you might come across situations where you need JavaScript to perform an action or execute a piece of code after waiting for a specific amount of time. In this blog post, we will explore how to make JavaScript wait for 5 seconds before executing a function or a block of code.

Using the setTimeout() Function

The setTimeout() function is a built-in JavaScript function that allows you to execute a function or a block of code after a specified amount of time (in milliseconds). To make JavaScript wait for 5 seconds, you can pass the time value as 5000 milliseconds to the setTimeout() function.

Here’s a basic example:

    setTimeout(function() {
        console.log('This message will be shown after 5 seconds');
    }, 5000);
    

In this example, the console.log() function will be executed after 5 seconds. You can replace the console.log() with any other function or code that you want to be executed after 5 seconds.

Using Async/Await and Promises

Another approach to make JavaScript wait for 5 seconds is by using async/await and Promises. This method is particularly useful when you want to pause the execution of a function for a certain amount of time.

First, create a function that returns a Promise, which resolves after 5 seconds:

    function waitFiveSeconds() {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve('5 seconds have passed');
            }, 5000);
        });
    }
    

Now, you can use async/await to call this function and make your code wait for 5 seconds before proceeding:

    async function executeAfterFiveSeconds() {
        console.log('Starting...');

        const result = await waitFiveSeconds();
        console.log(result);

        console.log('This message will be shown after 5 seconds');
    }

    executeAfterFiveSeconds();
    

In this example, the code inside the executeAfterFiveSeconds() function will wait for 5 seconds before continuing. You can adjust the time value in the setTimeout() function within the waitFiveSeconds() function to change the waiting time.

Conclusion

There are multiple ways to make JavaScript wait for a specific amount of time before executing a function or a block of code. The setTimeout() function and async/await with Promises are two commonly used methods for this purpose. Choosing between these methods depends on your specific use case and the structure of your code.