How to Wait 5 Seconds in JavaScript

You can use the following function to call your JavaScript code after a delay of N seconds:

function delay(seconds) { return new Promise((resolve) => { setTimeout(resolve, seconds * 1000); }); }
Code language: JavaScript (javascript)

To use this function, you can call it with a desired number of seconds, and then use the then() method of the returned promise to specify a callback function that will be executed when the promise resolves:

delay(5) .then(() => { console.log("The promise has resolved after 5 seconds!"); });
Code language: JavaScript (javascript)

Or, you can use await instead of then():

await delay(5); console.log("The promise has resolved after 5 seconds!");
Code language: JavaScript (javascript)

In this code, the delay() function is called with an argument of 5, which means that the promise will resolve after 5 seconds.

When the promise resolves, the callback function passed to the then() method will be executed, and the message “The promise has resolved after 5 seconds!” will be logged to the console.

How it Works

The delay function takes a single argument, seconds, which specifies the number of seconds to wait before resolving the promise.

It uses the setTimeout() function to schedule a resolution of the promise after the specified number of seconds have passed.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *