Skip to content

Instantly share code, notes, and snippets.

@hectorguo
Created October 19, 2018 22:25
Show Gist options
  • Save hectorguo/d69f09156b54514a65a2cbac903f0a56 to your computer and use it in GitHub Desktop.
Save hectorguo/d69f09156b54514a65a2cbac903f0a56 to your computer and use it in GitHub Desktop.
A simple debounce implementation
function debounce(fn, delay) {
let timer;
function helper(...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args); // keep the original context
}, delay);
}
return helper;
}
// ------------Test----------
// var test = {
// value: 'test',
// changeInput: function(key) {
// console.log('Input changed', key, this.value);
// }
// }
// test.changeInput = debounce(test.changeInput, 1000);
// for(let i = 0; i <= 10; i++) {
// test.changeInput(i);
// }
// Output 'Input changed', 10, 'test'
// Only triggered once.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment