How to delay execution of a JavaScript function

Delay Execution of a JavaScript Function

To delay the execution of a code in Java Script setTimeOut() is used, It is an asynchronous function which allows to schedule the code for specific delay.

Basic Syntax :

setTimeout(function-to-execute, time-delay-in-milliseconds);

Therefore to add time delay can be added to a function by providing the function and the time delay as per the syntax.

Example 1 :

function confirm(){
   console.log("User action is Confirmed");
}
setTimeout(confirm(), 2000);

In this code, we defined the function confirm() separately then called it inside the setTimeout() with a delay of 2000ms or 2 seconds.

If the function is only defined to be used in setTimeout(), then instead of defining the function seperately, we can use it as an anonymous function inside setTimeout() itself.

Example 2 :

setTimeout(() => { 
    console.log("User action is Confirmed");
    }, 2000);

Here instead of defining confirm() seperatly, It is defined directly in setTimeout() as an anonymous function, this format is used when the same function isn’t used anywhere else in the code.

 

Leave a Comment

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

Scroll to Top