Created
May 14, 2020 06:11
-
-
Save codinronan/fdf42104dd81534b96b95e8191c4df82 to your computer and use it in GitHub Desktop.
Vanilla JS throttle, vanilla JS debounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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