Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 14, 2022 05:30 pm GMT

What is Throttling? How to implement it in JS?

In the previous post we talked about debounce. Click on this link if you'd like to know about debouncing.

Throttling is a method used to limit the number of times a function can be executed.

Throttling - No matter how many times a function is fired, it will be executed only once in a given time interval

Let's say we have an expensive function which does heavy computation or calls a costly 3rd party API.

const expensive = () => {  console.log('Expensive function');}

We can limit the number of times the function can be executed by using throttling. Let's write a simple throttle function.

const throttle = (fn, delay) => {  let wait = false;  const throttledFunction = () => {    if (wait) return; // If wait is true, it means the timer// is still running and the function shouldn't be executed    fn();    wait = true;    setTimeout(() => {      wait = false;    }, delay);  return throttledFunction;}const inExpensive = throttle(expensive, 1000);

Our throttle function takes a callback function and delay and returns its throttled counterpart(inExpensive).

But wait, our throttle function cannot handle arguments. Let's improve it a bit so that it can take arguments.

const throttle = (fn, delay) => {  let wait = false;  let storedArgs = null;  const throttledFunction = (...args) => {    if (wait) {      storedArgs = args;      return    }    fn(...storedArgs);    wait = true;    setTimeout(() => {      wait = false;    }, delay);  }  return throttledFunction;}

Thanks for reading!....

https://medium.com/walkme-engineering/debounce-and-throttle-in-real-life-scenarios-1cc7e2e38c68
https://www.freecodecamp.org/news/javascript-debounce-example/
https://egghead.io/lessons/javascript-build-lodash-debounce-from-scratch


Original Link: https://dev.to/dileepreddyaella/what-is-throttling-how-to-implement-it-in-js-52d8

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To