Skip to content

Instantly share code, notes, and snippets.

@codinronan
Created May 14, 2020 06:11
Show Gist options
  • Save codinronan/fdf42104dd81534b96b95e8191c4df82 to your computer and use it in GitHub Desktop.
Save codinronan/fdf42104dd81534b96b95e8191c4df82 to your computer and use it in GitHub Desktop.
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