Enhancing User Experience with JavaScript Throttle and Debounce
![JavaScript Throttle and Debounce](https://www.jsmount.com/wp-content/uploads/2024/03/throttle-debounce-732x431.png)
JavaScript Throttle and Debounce
Throttle
In software development, particularly in the context of APIs or network requests, a throttle is a mechanism used to limit the rate at which requests or actions can be made.
When you want an event to happen only once in an interval & only the first event is used.
Understand Code
function throttleFn(innerFn, delay) {
let wait = false;
return function (...args) {
if (wait) {
console.log('waiting stage, cannot process further events.');
return;
}
innerFn(...args);
wait = true;
setTimeout(() => {
wait = false;
console.log('wait over, I am ready to process new event');
}, delay);
}
}
– Throttle function takes two arguments, first is function and second is a delay time.
– It returns a function, which means it forms a Closure.
– Inner function takes arguments that are required to execute callback.
– Now run the passed function and set the wait variable as true.
– Apply a check for the wait variable and if it is true then stop next all calling the same event.
– Mark this wait variable to false inside settimeout web API with passed delay time.
– And once it becomes false, it is ready to take the next event.
Example – User can apply the coupon one time only in a specific time interval.
let productValue = 100;
function apply20Coupon(discount) {
console.log("New price", productValue - (productValue * discount) / 100);
}
// coupon function is first parameter and timer is second parameter.
const fn = throttleFn(apply20Coupon, 2000);
fn(20); // will print new price
setTimeout(() => {
fn(20); // waiting stage, cannot process further events.
}, 1000);
setTimeout(() => {
fn(20); // waiting stage, cannot process further events. // wait over, I am ready to process new event
}, 1500);
setTimeout(() => {
fn(30); // will print new price
}, 2000);
Another Example of Throttle – Request limits how frequently the fetch method can be called to avoid overloading the server.
Debounce
Debouncing is another useful technique in programming, particularly in scenarios where you want to handle events that may be triggered rapidly, such as keyboard input or scroll events. Debouncing ensures that a function is only executed after a certain amount of time has passed since the last invocation of the function.
function debounce(fn, delay) {
let timerId = null;
return function (...args) {
if (timerId) {
clearInterval(timerId);
}
timerId = setTimeout(() => {
fn(...args);
}, delay);
}
}
– Debounce function makes sure that your code is only triggered once per user input.
– Debounce limits the rate at which a function gets invoked.
– It ensures that time-consuming tasks do not fire so often.
– When we want to limit the keystrokes for which We have to call some action.
In simple words Debounce is When we have an event or API calling on every key press or user input, then it hits that event only when the User stops typing.
Use of debouncing method –
function printHello() {
const d = new Date();
console.log("hello, I am debouncing, time is - ", d.getMilliseconds());
}
const debouncedPrintHello = debounce(printHello, 1000);
// Here we are firing events constantly so only last one will be fired, rest all will be ignored.
debouncedPrintHello();
debouncedPrintHello();
debouncedPrintHello();
// This event is fired after some delay so it will consider.
setTimeout(() => {
debouncedPrintHello();
}, 1000);
Difference between Debounce & Throttle –
Debounce process last event and Throttle process first event.
Debounce waits till the User stops providing input & then hits the event, Throttle first hits the event and then waits till the provided wait period.
JavaScript Throttle and Debounce
- Unlocking the Secrets of Cookie | Power Your Web Experience
- AI vs Human: Exploring the Boundaries of Intelligence
- Enhancing User Experience with JavaScript Throttle and Debounce
- JavaScript Custom Promise | Promise Polyfill
- JavaScript Promisify | Convert Callbacks to Promises
- JavaScript Promise and Callbacks | Everything You Must Know
- CSS Display Property – Deep dive in block | inline | inline-block
- Implementation of Queue using Linked List | JavaScript
- Insert node in Linked list | Algorithm | JavaScript
- Insertion Sort in data structure | Algorithm with Examples
- Selection Sort Algorithm & K’th Largest Element in Array
- Quick Sort Algorithm with example | Step-by-Step Guide
- Dependency Inversion Principle with Example | Solid Principles
- Object-Oriented Programming | Solid Principles with Examples
- ASCII Code of Characters | String Operations with ASCII Code
- Negative Binary Numbers & 2’s Complement | Easy explanation
- Factors of a Number | JavaScript Program | Optimized Way
- LeetCode – Game of Life Problem | Solution with JavaScript
- Fibonacci series using Recursion | While loop | ES6 Generator
- JavaScript Coding Interview Question & Answers
- LeetCode – Coin Change Problem | Dynamic Programming | JavaScript
- HackerRank Dictionaries and Maps Problem | Solution with JavaScript
- React Redux Unit Testing of Actions, Reducers, Middleware & Store
- Micro frontends with Module Federation in React Application
- React Interview Question & Answers – Mastering React
- Top React Interview Question & Answer | React Routing
- React Interview Questions and Answers | React hooks
- Higher Order Component with Functional Component | React JS
- Top React Interview Questions and Answers | Must Know
- Interview Question React | Basics for Freshers and Seniors