Skip to content

Instantly share code, notes, and snippets.

@vlepeule
Last active February 2, 2017 16:25
Show Gist options
  • Save vlepeule/94d139756944a5013f4dafd737be5a90 to your computer and use it in GitHub Desktop.
Save vlepeule/94d139756944a5013f4dafd737be5a90 to your computer and use it in GitHub Desktop.
Debounce & throttle javascript function
function debounce(callback, delay){
var timer;
return function(){
var args = arguments;
var context = this;
clearTimeout(timer);
timer = setTimeout(function(){
callback.apply(context, args);
}, delay)
}
}
function throttle(callback, delay) {
var last;
var timer;
return function () {
var context = this;
var now = +new Date();
var args = arguments;
if (last && now < last + delay) {
// le délai n'est pas écoulé on reset le timer
clearTimeout(timer);
timer = setTimeout(function () {
last = now;
callback.apply(context, args);
}, delay);
} else {
last = now;
callback.apply(context, args);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment