Open In App

How to Delay a JavaScript Function Call using JavaScript ?

Last Updated : 12 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

When we want to call a function after a described amount of time, we use a delay function in JavaScript.

There are several ways to delay the execution of a function. This can be useful for various purposes, such as creating animations, implementing debounce in search inputs, or simply delaying an action until a certain condition is met.

Using setTimeout() Method

The most common way to delay a function in JavaScript is by using the setTimeout() function. This function allows you to specify a delay (in milliseconds) after which a function will be executed.

Example: This example shows the use of the setTimeout() method to delay the function call in JavaScript. In this example, myGeeks() function will be executed after a delay of 3 seconds (3000 milliseconds).

Javascript
function myGeeks() {
    console.log("Function executed after 3 seconds");
}

setTimeout(myGeeks, 3000);

Output

Function executed after 3 seconds

Using Promises and async/await

You can also create a delay using Promises and the async/await syntax. This approach is useful when you want to use delay within an asynchronous function.

Example: In this example, the delay function returns a Promise that resolves after a specified number of milliseconds. The myGeeks uses await to pause its execution until the delay is completed.

Javascript
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function myGeeks() {
    console.log("Waiting 2 seconds...");
    await delay(2000);
    console.log("Function executed after 2 seconds");
}

myGeeks();

Output

Waiting 2 seconds...
VM141:8 Function executed after 2 seconds

Using setInterval() for Repeated Delays

If you need to repeatedly delay a function at fixed intervals, you can use setInterval() method.

Example: In this example, mtGeeks will be executed every 1 second (1000 milliseconds).

Javascript
function myGeeks() {
    console.log("Function executed every 1 second");
}

setInterval(myGeeks, 1000);

Output

Function executed every 1 second
Function executed every 1 second
. . .

Canceling a Delay

You can cancel a delay created with setTimeout() or setInterval() using clearTimeout() and clearInterval() respectively.

Example: In this example, the execution of the function passed to setTimeout() is canceled before it has a chance to execute.

Javascript
let timeoutId = setTimeout(() => {
    console.log("This will not be executed");
}, 3000);

clearTimeout(timeoutId);

Output

Function executed every 1 second

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads