How to wait n seconds in JavaScript

Aug 03, 2023#javascript#how-to

There are different ways to wait n seconds in JavaScript, but one of the most common ones is to use the setTimeout() method. This method allows you to execute a function or a code block after a specified amount of time, which you can set in milliseconds.

For example, if you want to wait 5 seconds before executing the next line, you can write something like this:

// this code will run first
console.log("Hello");

// this code will run after 5 seconds
setTimeout(function() {
  console.log("World");
}, 5000);

You can also use an arrow function instead of a regular function as the first argument of setTimeout():

// this code will run first
console.log("Hello");

// this code will run after 5 seconds
setTimeout(() => {
  console.log("World");
}, 5000);

Another option is to use the async/await syntax, which lets you write asynchronous code in a more synchronous way. You can create a function that returns a promise that resolves after a certain amount of time, and then use the await keyword to pause the execution until the promise is fulfilled. For example:

// this function returns a promise that resolves after n milliseconds
const wait = (n) => new Promise((resolve) => setTimeout(resolve, n));

// this is an async function that uses await to pause the execution
const sayHelloWorld = async () => {
  // this code will run first
  console.log("Hello");

  // this code will wait for 5 seconds
  await wait(5000);

  // this code will run after 5 seconds
  console.log("World");
};

// call the async function
sayHelloWorld();

The setTimeout() function returns a value that identifies the timer created by it. You can use this value with the clearTimeout() method to cancel the timer and prevent the function from executing. For example:

// this code will create a timer that displays an alert message after 3 seconds
var timer = setTimeout(function() {
  alert("Hello!");
}, 3000);

// this code will cancel the timer and prevent the alert message
clearTimeout(timer);

The setTimeout() function is useful for creating timing events, such as animations, countdowns, clocks, etc. However, it is important to note that the setTimeout() function is asynchronous, meaning that it does not block the execution of other code. Also, the actual delay may be longer than the specified time, depending on the browser and the system performance.