Skip to content

Instantly share code, notes, and snippets.

@ppscvalentin
Created August 22, 2017 08:15
Show Gist options
  • Save ppscvalentin/c69dd902e0e0f3adcce3edb0623450d4 to your computer and use it in GitHub Desktop.
Save ppscvalentin/c69dd902e0e0f3adcce3edb0623450d4 to your computer and use it in GitHub Desktop.
debounce, throttle
// https://davidwalsh.name/function-debounce
debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// https://remysharp.com/2010/07/21/throttling-function-calls
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment