Throttling in JS

Throttling

Throttling in JavaScript is a technique used to control the rate at which a function is executed.
This is especially useful in scenarios where a function could be called frequently, such as during scroll events, window resizing,…


This content originally appeared on DEV Community and was authored by Margish Patel

Throttling

  • Throttling in JavaScript is a technique used to control the rate at which a function is executed.

  • This is especially useful in scenarios where a function could be called frequently, such as during scroll events, window resizing, or handling user input in real-time.

  • By throttling a function, you ensure that it is not executed more often than a specified interval, thereby improving performance and responsiveness of the application.

boy-throttles-bike

Ok ok we will not go into too much of theories and stuff but just remember that throttling means preventing a functional call which might called continuously.

Here's how throttling works...

  • So we have to just wrap our function into custom function which is implemented on top of setTimeout()

Have you ever work around closure concept of Javascript ?

if no then this might look confusing...

Step 1 : Main body of our wrapper function.

function throttle(func, delay) {
    return function (...args) {
        return func(...args);
    };
}

we will call this wrapper function like this :

function callApi() {
   // here comes the api call logic or any work you want to throttle.
}

const throttledFunction = throttle(callApi, 3000) // 3 in seconds

Step 2 : Now we add timer to this function ⏰

  • In next step we will understand why we are getting this timestamp.
function throttle(func, delay) {
    return function (...args) {
        const now = new Date().getTime(); // getting the timestamps

        return func(...args);
    };
}

Step 3 : Some logic

  • In here we have something interesting. I mean how do we compare old time with new one ? we probably need some logic right ?
  • so here the actual part which is helping the wrapper function to call our passed function only and only if certain delay is passed.
  • We have to keep track of lastCall which is initially 0.
  • we update this lastCall every time with current time, in our case we set it with now.
function throttle(func, delay) {
    let lastCall = 0;
    return function (...args) {
        const now = new Date().getTime(); // getting the timestamps
        lastCall = now;
        return func(...args);
    };
}

step 4 : Putting some condition which adds throttle behaviour

  • we must have to compare our old time and new timer with passed delay time and if it is less than passed delay time then we have to return our function right away so out actual function will not call this time.
  • it will wait for another time when this throttled function fires.
function throttle(func, delay) {
    let lastCall = 0;
    return function (...args) {
        const now = new Date().getTime(); // getting the timestamps
        if(now - lastCall < delay) {
          return;  
        }

        lastCall = now;
        return func(...args);
    };
}

NOTE: Sometime you might mess up around comparing timing in if statement so i would suggest you to wrap your subtraction line with abs(now - lastCall) < delay So we are on same line.

TIP of the day 💡 : Its always good idea to write readable code so i would highly prefer you to give appropriate name and naming convention should be constant to your entire code base.

Conclution 🍫 🍩

Yo buddy, Congratulations ! 🎉 you just made your own throttling function. Go and use it in your code base.

Reach out to me if you have any queries. I would love to answer you questions.


This content originally appeared on DEV Community and was authored by Margish Patel


Print Share Comment Cite Upload Translate Updates
APA

Margish Patel | Sciencx (2024-06-23T19:16:10+00:00) Throttling in JS. Retrieved from https://www.scien.cx/2024/06/23/throttling-in-js/

MLA
" » Throttling in JS." Margish Patel | Sciencx - Sunday June 23, 2024, https://www.scien.cx/2024/06/23/throttling-in-js/
HARVARD
Margish Patel | Sciencx Sunday June 23, 2024 » Throttling in JS., viewed ,<https://www.scien.cx/2024/06/23/throttling-in-js/>
VANCOUVER
Margish Patel | Sciencx - » Throttling in JS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/06/23/throttling-in-js/
CHICAGO
" » Throttling in JS." Margish Patel | Sciencx - Accessed . https://www.scien.cx/2024/06/23/throttling-in-js/
IEEE
" » Throttling in JS." Margish Patel | Sciencx [Online]. Available: https://www.scien.cx/2024/06/23/throttling-in-js/. [Accessed: ]
rf:citation
» Throttling in JS | Margish Patel | Sciencx | https://www.scien.cx/2024/06/23/throttling-in-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.