Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vanilla JS throttle, vanilla JS debounce
// https://vanillajstoolkit.com/helpers/debounce/
var debounce = function (fn) {
// Setup a timer
var timeout;
// Return a function to run debounced
return function () {
// Setup the arguments
var context = this;
var args = arguments;
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup the new requestAnimationFrame()
timeout = window.requestAnimationFrame(function () {
fn.apply(context, args);
});
}
};
// doing this to show/hide the tooltips based on mobile size.
function throttle(func, alternateFunc, minimumInterval) {
var executeImmediately = true, freshEvt = null;
return function (Evt) {
if (executeImmediately) { // Execute immediately
executeImmediately = false;
setTimeout(function (f) { // handle further calls
executeImmediately = true;
if (freshEvt !== null) func(freshEvt);
freshEvt = null;
}, minimumInterval);
return func(Evt);
} else { // Delayed execute
freshEvt = Evt;
if (typeof alternateFunc === "function") alternateFunc(Evt);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment