Skip to content

Instantly share code, notes, and snippets.

@kurtextrem
Created October 5, 2016 08:35
Show Gist options
  • Save kurtextrem/d3dbb385662cb013fb99cb5b80da334d to your computer and use it in GitHub Desktop.
Save kurtextrem/d3dbb385662cb013fb99cb5b80da334d to your computer and use it in GitHub Desktop.
Simple and small Throttle & debounce functions

Example usage

Throttle

$(window).on('scroll.namespace', throttle(function () { console.log('call') }, 200));

Debounce

$(window).on('resize.namespace', debounce(function () { console.log('call') }, 100));

// no leading call, only trailing
function debounce(callback, timeout, _time) {
timeout = timeout || 100;
return function debounce() {
window.clearTimeout(_time);
_time = window.setTimeout(callback, timeout);
}
}
// leading call if event occurs `wait` ms after calling `throttle`
function throttle(callback, wait, _time) {
wait = wait || 200;
_time = Date.now();
return function throttle() {
if ((_time + wait - Date.now()) < 0) {
callback();
_time = Date.now();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment