How to Set a Time Delay in JavaScript

To set a time delay in JavaScript, you can use the “setTimeout()” function. The “setTimeout()” function allows you to execute a function or code after a specified delay.

Syntax

setTimeout(functionToExecute, delayInMilliseconds, arg1, arg2, ...);

Parameters

  1. functionToExecute: The function you want to execute after the specified delay.
  2. delayInMilliseconds: The delay in milliseconds before the function is executed.
  3. arg1, arg2, …: Optional arguments to be passed to the function when executed.

Example

function greet(name) {
  console.log('Hello, ' + name + '!');
}

setTimeout(greet, 2000, 'John');

You can also use an anonymous function or an arrow function as the functionToExecute:

setTimeout(() => {
  console.log('This message will be displayed after a 3-second delay');
}, 3000);

Remember that the setTimeOut() method is a non-blocking function, which means that the rest of your code will continue to execute while waiting for the specified delay to elapse.

Leave a Comment