Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to write a function in JavaScript ?
Next article icon

How to Delay a JavaScript Function Call using JavaScript ?

Last Updated : 21 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Table of Content

  • Using setTimeout() Method
  • Using Promises and async/await
  • Using setInterval() for Repeated Delays
  • Canceling a Delay

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

Next Article
How to write a function in JavaScript ?

V

vkash8574
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

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 get currently running function name using JavaScript ?
    Given a function and the task is to get the name of function that is currently running using JavaScript. Approach 1: Using arguments.callee method: It refers to the currently executing function inside the function body of that function. In this method, we use arguments.callee to refer to the name of
    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 write a function in JavaScript ?
    JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
    4 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
  • 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
  • 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 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 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 d
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences