Skip to content

Instantly share code, notes, and snippets.

@kerimdzhanov
Created April 1, 2020 00:29
Show Gist options
  • Save kerimdzhanov/22869075ba184287af0f04ba54771551 to your computer and use it in GitHub Desktop.
Save kerimdzhanov/22869075ba184287af0f04ba54771551 to your computer and use it in GitHub Desktop.
JavaScript Throttling vs Debouncing

Throttling vs Debouncing

Throttling is a straightforward reduction of the trigger rate. It will cause the event listener to ignore some portion of the events while still firing the listeners at a constant (but reduced) rate.

Unlike throttling, debouncing is a technique of keeping the trigger rate at exactly 0 until a period of calm and then triggering the listener exactly once.

In other words

With Throttling the original function is called at most once per specified period.

With Debouncing the original function is called after the caller stops calling the decorated function after a specified period.


Throttle 1 sec Debounce 1 sec
Just after triggering emits the original function counts down delay for 1 sec
Subsequent triggers (< 1 sec) have no effects restarts delay for 1 sec
Emits the original function if the last emit was in more than 1 sec there were no triggers during the last 1 sec
/**
* Create a debounced function.
*
* @param {function} fn - callback function
* @param {number} delay - in milliseconds
* @return {function} debounce trigger
*/
function debounced(fn, delay) {
let timerId;
return function (...args) {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn(...args);
timerId = null;
}, delay);
}
}
/**
* Create a throttled function.
*
* @param {function} fn - callback function
* @param {number} delay - in milliseconds
* @return {function} throttle trigger
*/
function throttled(fn, delay) {
let lastCall = 0;
return function (...args) {
const now = (new Date).getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return fn(...args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment