Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • 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 change video playing speed using JavaScript ?
Next article icon

JavaScript Throttling

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Throttling is a technique used to limit the number of times a function can be executed in a given time frame. It’s extremely useful when dealing with performance-heavy operations, such as resizing the window or scrolling events, where repeated triggers can lead to performance issues.

JavaScript
function throttle(fn, delay) {
    let lastTime = 0;
    return function (...args) {
        let now = Date.now();
        if (now - lastTime >= delay) {
            fn.apply(this, args);
            lastTime = now;
        }
    };
}

In this example

  • The throttle function takes a function (fn) and a delay (delay) as parameters.
  • It keeps track of the last execution time using lastTime.
  • When the function is called, it checks if the time difference from the last execution is greater than or equal to the delay.
  • If so, it executes the function and updates lastTime.

Why is Throttling Needed?

Certain user interactions, like scrolling or window resizing, trigger events multiple times per second. Executing event handlers at such a high frequency can lead to performance issues, including:

  • Increased CPU and memory usage.
  • Unresponsive user interfaces.
  • Inefficient API calls leading to server strain.

By throttling a function, we can ensure it executes at a controlled rate, reducing resource consumption and improving responsiveness.

How Throttling Works

Throttling works by restricting the execution of a function so that it runs at most once every predefined period, even if the event is triggered multiple times within that interval.

  1. A function is triggered multiple times due to an event (e.g., scroll, resize).
  2. Throttling ensures that the function executes only once within the defined interval.
  3. Any additional triggers during the interval are ignored until the next cycle starts.
  4. Once the interval is over, the function can execute again if triggered.

Implementing Throttling in JavaScript

1. Using setTimeout

A simple way to implement throttling is by using setTimeout. The function execution is delayed and only runs after the specified time interval has passed.

JavaScript
function throttle(fn, delay) {
    let isThr = false;

    return function (...args) {
        if (!isThr) {
            fn.apply(this, args);
            isThr = true;

            setTimeout(() => {
                isThr = false;
            }, delay);
        }
    };
}

window.addEventListener('scroll', throttle(() => {
    console.log('Scroll event triggered!');
}, 1000));

2. Using Date.now()

Another approach is to use Date.now() to keep track of the last execution time and determine when the function should be called again.

JavaScript
function throttle(fn, delay) {
    let t = 0;
    return function (...args) {
        let now = Date.now();
        if (now - t >= delay) {
            fn.apply(this, args);
            t = now;
        }
    };
}
window.addEventListener('resize', throttle(() => {
    console.log('Resize event triggered!');
}, 500));

Difference Between Throttling and Debouncing

Both throttling and debouncing are techniques for controlling function execution, but they serve different purposes:

FeatureThrottlingDebouncing
Execution ControlEnsures function runs at most once per intervalDelays function execution until event stops
Best Use CasesScroll events, API calls, keypress handlingSearch input, auto-save, form validation
Frequency of ExecutionRuns at regular intervalsRuns only once after a delay

Use Cases of Throttling

Throttling is commonly used in cases where frequent execution of a function can cause performance issues.

  • Handling Scroll Events: Optimizing infinite scrolling by limiting API calls.
  • Window Resize Events: Preventing excessive recalculations and re-renders.
  • API Rate Limiting: Ensuring a function making API requests does not exceed allowed limits.
  • Mouse Move Events: Improving efficiency in drag-and-drop interactions.

Throttling
Visit Course explore course icon
Next Article
How to change video playing speed using JavaScript ?

T

tarun007
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics

Similar Reads

    Foundation CSS JavaScript Throttle Utility
    Foundation CSS is an open-source front-end framework that is used to create a beautiful responsive website, apps, or email quickly and easily. ZURB published it in September of that year. Numerous businesses, like Facebook, eBay, Mozilla, Adobe, and even Disney, make use of it. This framework, which
    2 min read
    Lodash _.throttle() Method
    The Lodash _.throttle() method limits a function’s execution to once every specified time interval, preventing it from being called too frequently. It’s ideal for performance optimization in events like scrolling or resizing, with built-in methods to cancel or immediately invoke delayed calls.Moreov
    3 min read
    How to change video playing speed using JavaScript ?
    In this article, we will see how we can change the playback speed of videos embedded in an HTML document using an HTML5 video tag.We can set the new playing speed using the playbackRate attribute. It has the following syntax.Syntax:let video = document.querySelector('video')video.playbackRate = newP
    1 min read
    How to change video playing speed using JavaScript ?
    In this article, we will see how we can change the playback speed of videos embedded in an HTML document using an HTML5 video tag.We can set the new playing speed using the playbackRate attribute. It has the following syntax.Syntax:let video = document.querySelector('video')video.playbackRate = newP
    1 min read
    Difference between Debouncing and Throttling
    Debouncing and throttling are techniques used to optimize the performance of functions triggered by events that occur frequently, such as scrolling, resizing, or typing. They help in managing how often these functions are executed, which can improve user experience and system performance. Here’s a d
    4 min read
    Underscore.js _.throttle() Function
    The _.throttle() method in underscore is used to create a throttled function that can only call the func parameter maximally once per every wait milliseconds. The throttled function has a cancel method which is used to cancel func calls that are delayed and it also has a flush method which is used t
    2 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
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
  • DSA Tutorial
  • 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