Last active
February 2, 2017 16:25
-
-
Save vlepeule/94d139756944a5013f4dafd737be5a90 to your computer and use it in GitHub Desktop.
Debounce & throttle javascript function
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
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