How to Delay a JavaScript Function Call using JavaScript ?
Last Updated :
21 Aug, 2024
Delaying a JavaScript function call involves postponing its execution for a specified time using methods like setTimeout(). This technique is useful for timed actions, animations, or asynchronous tasks, enabling smoother user experiences and better control over when certain operations run.
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 setTimeout() method delays a function's execution by a specified time in milliseconds. It takes a callback function and a delay value, running the function once after the delay elapses.
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
Using Promises and async/await, you can delay a function by creating a Promise that resolves after a set time with setTimeout(). Use await to pause execution until the delay completes.
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
The setInterval() method repeatedly executes a function at specified intervals in milliseconds until cleared. Unlike setTimeout(), it runs continuously at set intervals, ideal for tasks requiring consistent updates, like animations or periodic data fetching.
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
To cancel a delayed function call set by setTimeout(), use the clearTimeout() method. Pass the identifier returned by setTimeout() to stop the scheduled function from executing, effectively canceling the delay.
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
Similar Reads
How to Delay a Function Call in JavaScript ?
Delaying a JavaScript function call involves executing a function after a certain amount of time has passed. This is commonly used in scenarios where you want to postpone the execution of a function, such as in animations, event handling, or asynchronous operations. Below are the methods to delay a
2 min read
How to call function from it name stored in a string using JavaScript ?
In this article, we will call a function from the string stored in a variable. There are two methods to call a function from a string stored in a variable. Using window object methodUsing eval() method Note: The eval() method is older and is deprecated. Method 1: Using the window object. The window
2 min read
How to measure time taken by a function to execute using JavaScript ?
This article will show how to measure the time taken by a function to execute using Javascript. To measure the time taken by a function to execute we have three methods: Table of Content Using the Using Date ObjectUsing the performance.now() methodUsing the console.time() methodMethod 1: Using the U
3 min read
How to Call a JavaScript Function from an onsubmit Event ?
The onsubmit event attribute in HTML is triggered when a form is submitted. It is also useful for validating form data or performing actions before any submission and ensures better control and validation of user inputs before data is sent. The below methods can be used to call a JavaScript function
2 min read
How to override a JavaScript function ?
In this article, we are given an HTML document and the task is to override the function, either a predefined function or a user-defined function using JavaScript. Approach: When we run the script then Fun() function is called. After clicking the button the GFG_Fun() function is called and this funct
2 min read
Passing a function as a parameter in JavaScript
In this article, we will pass a function as a parameter in JavaScript. Passing a function as an argument to the function is quite similar to passing a variable as an argument to the function. So variables can be returned from a function. The below examples describe passing a function as a parameter
1 min read
How to call a function repeatedly every 5 seconds in JavaScript ?
In JavaScript, the setInterval() method allows you to repeatedly execute a function or evaluate an expression at specified intervals. This method is particularly useful for performing periodic tasks like updating a user interface or making repeated API calls. Syntax:Â setInterval(function, millisecon
2 min read
JavaScript Passing parameters to a callback function
Callback FunctionPassing a function to another function or passing a function inside another function is known as a Callback Function. In other words, a callback is an already-defined function that is passed as an argument to the other code Syntax:function geekOne(z) { alert(z); }function geekTwo(a,
2 min read
How does call stack handle function calls in JavaScript ?
In this article, we will see how the call stack in JavaScript handles the functions in a JavaScript program. Call StackCall Stack in any programming language is a fundamental concept responsible for the execution of function calls made in the program. While execution it also manages their order of e
2 min read
JavaScript Complete Guide - A to Z JavaScript Concepts
JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for web pages. Some of the key features of JavaScript are: Lightweight and Fast: JavaScript is a lightweight programming language that runs quickly
6 min read