Created
October 19, 2018 22:25
-
-
Save hectorguo/d69f09156b54514a65a2cbac903f0a56 to your computer and use it in GitHub Desktop.
A simple debounce implementation
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(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