Skip to content

Instantly share code, notes, and snippets.

@nikola-wd
Last active December 6, 2020 16:17
Show Gist options
  • Select an option

  • Save nikola-wd/f28d0f68843910e8fa841d6bafbf9179 to your computer and use it in GitHub Desktop.

Select an option

Save nikola-wd/f28d0f68843910e8fa841d6bafbf9179 to your computer and use it in GitHub Desktop.
[debounce] Useful for not making requests on every key stroke for example #havascript #helper #optimization
// send req after a few seconds have passed since user last wrote in the editor
export default function debounce(a,b,c){
let d,e;
return function(){
function h(){
d=null;
c||(e=a.apply(f,g));
}
let f=this,g=arguments;
return (clearTimeout(d),d=setTimeout(h,b),c&&!d&&(e=a.apply(f,g)),e)
}
}
// Call it like this (Wait for 1.5s)
debounce(() => {}, 1500);
// ABOVE DOESN'T WORK. USE THIS ONE:
var debounce = function debounce(func, wait) {
var timeout;
return function executedFunction() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var later = function later() {
clearTimeout(timeout);
func.apply(void 0, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment