Open In App

How to Delay a JavaScript Function Call using JavaScript ?

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 JavaScript function call: Table of Content Using s
2 min read
Program to swap two integer parameters using call by value & call by address in PHP ?
Call by value: In call by value, we will send the value from the calling function to the called function. The values of the calling function arguments are directly copied to the corresponding arguments of the called function. If any modification is done on the arguments of the called function, it will not be effected on the arguments of the calling
3 min read
Call by Value Vs Call by Reference in JavaScript
Call by Value: In this method, values of actual parameters are copied to the function’s formal parameters, and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in the actual parameters of the caller. Suppose there is a variable named “a”. Now, we store a primitive value(boo
3 min read
How to execute setInterval function without delay for the first time in JavaScript ?
The setInterval() method always invokes the function after the delay for the first time using two approaches: Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set
2 min read
How to redirect to multiple websites with a delay using JavaScript ?
We have given multiple websites and the task is to redirect to multiple websites with some delay using JavaScript. We will use setTimeout() function to delay the website. setTimeout() Function: The setTimeout() method executes a function, after waiting a specified number of milliseconds. The first parameter is a command/function to be executed and
2 min read
How to delay a loop in JavaScript using async/await with Promise ?
Given below is a JavaScript code snippet which is basically described how to delay a loop in JavaScript using async/await. In this article, we are using JavaScript either the web browser or Node.js. We all face a difficult situation in delaying a loop in JavaScript unlike C++ where we have sleep() function, but there is nothing like this in JavaScr
2 min read
How To Create a Delay Function in ReactJS ?
Delay functions in programming allow for pausing code­ execution, giving deve­lopers precise control over timing. These functions are essential for tasks such as content display, animations, synchronization, and managing asynchronous operations. In this article, we will discuss how can we create a delay function in ReactJs. Pre-requisitesIntroducti
3 min read
Underscore.js _.delay() Function
Underscore.js _.delay() function executes the mentioned function in its argument after waiting for the specified milliseconds. It is mostly used when we want to perform some task but after a certain amount of time. In this case, we can define this function, and then it will be executed after the wait milliseconds. If we pass the arguments also to t
4 min read
How to add a delay in a JavaScript loop?
JavaScript doesn't offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a specified number of milliseconds. Below given example illustrates how to add a delay to various loops: For loop:[GFGTABS] JavaScript for (let i=0; i<10; i++) { task(i); } function task(i
3 min read
How to call a function that return another function in JavaScript ?
The task is to call a function that returns another function with the help of JavaScript is called a Currying function, a function with numerous arguments that can be converted into a series of nesting functions with the help of the currying method. Approach:Define Outer Function:Create an outer function that takes parameters and contains the logic
2 min read
jQuery UI Selectable delay Option
jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery JavaScript Library. jQuery UI is great for building UI interfaces for the webpages. It can be used to build highly interactive web applications or can be used to add widgets easily. The jQuery UI Selectable delay option is used to add the time delay in millisecon
1 min read
p5.js Image delay() Method
The delay() method of p5.Image in p5.js is used to change the delay between each frame in a GIF animation. This value can be set in milliseconds and a higher value would mean that the GIF would show its next frame after a longer time. An optional second parameter can be used to specify the index of the frame that needs to have the new delay value s
2 min read
jQuery UI Autocomplete delay Option
jQuery UI Autocomplete delay option is used to set the time after which the suggestion will be shown to the user. The default value is 300. Syntax: $( ".selector" ).autocomplete({delay: 300})Approach: First, add jQuery Mobile scripts needed for your project. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></scrip
1 min read
jQuery UI Sortable delay Option
jQuery UI sortable widget delay option is used to set the time in milliseconds to define when the sorting should start. Syntax: $( ".selector" ).sortable({ delay: 150 }); Approach: First, add jQuery UI scripts needed for your project. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://
1 min read
jQuery UI Resizable delay Option
The jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Resizable delay Option is used to add some delay to resize an element. Syntax: $(".selector").resizable({ delay: number }); CDN Link: First, add jQuery UI scripts ne
1 min read
jQuery UI Draggable delay Option
The jQuery UI consists of GUI widgets, visual effects, and themes implemented using jQuery, CSS, and HTML. jQuery UI is great for building UI interfaces for the webpages. The jQuery UI Draggable delay option is used to set the delay time to dragging the element. Syntax: $( ".selector" ).draggable({ delay: time }); CDN Link: First, add jQuery UI scr
1 min read
How to use animation-delay in CSS ?
In this article, we will see how to use the animation-delay property in CSS. The animation-delay property is used to set the animations on the web pages. The animation-delay property tells us about the delay in the start of an animation.The animation-delay value is defined in milliseconds (ms) or seconds (s).Its default value is 0 seconds.The prope
2 min read
jQWidgets jqxButton delay Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxButton is used to illustrate a jQuery button widget that enables us to show a button on the desired web page. The delay property is used to specify the pause
2 min read
What is the use of delay() method in jQuery ?
In this article, we will see how to use the delay() method and why to use it in jQuery. The delay() method is used to set a timer to delay the execution of the next item in the queue. Syntax: $(selector).delay(para1, para2); In the below example, first, we create a div of size 250px X 200px and set its display property to none. Also, created a butt
1 min read
jQWidgets jqxSortable delay Property
jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful and optimized framework, platform-independent, and widely supported. jqxSortable represents a jQuery plugin which allows you to reorder elements in a HTML list or div tags using the mouse. The delay property is used to set or retur
1 min read
How to delay document.ready() method until a variable is set in jQuery ?
In this article, we will learn to delay document.ready until a variable is set. The document.ready() method is used to execute some jQuery or JavaScript scripts when the HTML DOM is completely loaded. There are two approaches that can be followed here: Approach 1: Using the holdReady() method in the jQuery library and the setTimeout() method. First
3 min read
How to use keyup with delay in jQuery ?
In this article, we will see how to use keyup with a delay in jQuery. There are two ways to achieve the same: Approach 1: Using the keypress(), fadeIn(), delay() and fadeOut() methods in the jQuery library and clearTimeout() and setTimeout() methods in native JavaScript. Firstly, a variable keyupTimer with the keyword "let" is declared such that a
4 min read
Primer CSS Tooltips with No Delay
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
2 min read
Angular PrimeNG Tooltip Delay
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will see how to use the Tooltip events in Angular PrimeNG. Angular PrimeNG Tooltip Delay is used to show or hide tooltips quickly
3 min read
jQuery delay() Method
jQuery delay() method is an inbuilt that is used to set a timer to delay the execution of the next item in the queue.  Syntax:$(selector).delay(para1, para2);Parameter: It accepts two parameters which are specified below: para1: It specifies the speed of the delay.para2: It is optional and specifies the name of the queue.Return Value:It returns the
2 min read
How to Create an Observable with a Delay in TypeScript ?
Creating observables with delays is a common requirement in TypeScript applications, especially when dealing with asynchronous operations. To achieve this, we leverage the power of the rxjs library. What is rxjs library?The RxJS library is a powerful reactive programming library for JavaScript and TypeScript. It provides a set of tools for working
3 min read
How to Set Time Delay in PHP ?
To set a time delay in PHP, you have several approaches depending on your requirements. The time delay is useful for various purposes like creating a pause in script execution or scheduling tasks. These are the following different approaches: Table of Content Using sleep() FunctionUsing usleep() FunctionUsing while loopUsing DateTime() ObjectUsing
2 min read
Tailwind CSS Transition Delay
This class accepts lots of value in tailwind CSS in which all the properties are covered as in class form. The transition delay class is used to specify the length of time (in seconds or milliseconds) to start the transition effect. In CSS, we have done that by using the CSS transition-delay. Transition Delay classes:delay-75: This class is used to
2 min read
CSS animation-delay Property
The animation-delay property specifies a delay for the start of an animation. Defined in seconds (s) or milliseconds (ms), this value determines how long to wait before beginning the animation. Negative values start the animation as if it had already been playing for the specified duration. Syntaxanimation-delay: time|initial|inherit;Property Value
3 min read
CSS transition-delay Property
The transition-delay property in CSS specifies the delay time before a transition effect begins. It controls when the transition starts after a change has been initiate Use transition-delay to sequence transitions or to synchronize them with other animations or events on the page. It allows for precise timing control over animation effects. Syntaxt
3 min read