How to delay a JavaScript function call using JavaScript?

we are going to learn how can we delay a function in JavaScript. Whenever we want to call a function after a specified amount of time than we use the delay function in JavaScript.

To provide delay in JavaScript function we use a global window object named as setTimeout(). This function allows us to provide a specific delay before executing a function.

Let’s deep down into some of the functionalities, syntax and many other things of setTimeout() function. The setTimeout() method mainly require two one is the function which we need to execute with some delay and the other argument is the time for which we want to delay the function.

Syntax

Syntax to delay a function in JavaScript is given as −

When function declared inside the setTimeout() method:
setTimeout ( function(){function_body}, time in milliseconds);
   or
When function declared outside setTimeout() method:
function function_name();
setTimeout(function_name, time i
n milliseconds);

As the function declared in the setTimeout() method is anonymous so we can also remove the function keyword and replace it with the arrow function like shown below −

setTimeout(()=>{function_body}, time in milliseconds);

Related Posts

Top String Functions / Methods in JavaScript

Regular Expression in JavaScript for password validation with special character and number and string.

Password Validation in JavaScript / React

Minimum eight characters, at least one letter, one number and one special character: let ppattern = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/ Regular Expression in JavaScript for password validation with special character…

What are custom events in JavaScript?

Custom events are the events that allow you to decouple the code you want to run after a specific piece of code runs. There are various in-built events…

How to use nested for loop in JavaScript?

We use the for loop statement of JavaScript for repeating a set of statements inside the loop body a specified number of times. A nested for loop, as the…

What are the basic rules for JavaScript parameters?

A JavaScript function is a code that performs a particular task. The function parameters are the name list in the function definition. Parameters are also known as…

How to stop refreshing the page on submit in JavaScript?

Using event.preventDefault() to stop page refresh on form submit In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default…