An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
What is Throttling? How to implement it in JS?
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To