1// Returns a function, that, as long as it continues to be invoked, will not
2// be triggered. The function will be called after it stops being called for
3// N milliseconds. If `immediate` is passed, trigger the function on the
4// leading edge, instead of the trailing.
5function debounce(func, wait, immediate) {
6 var timeout;
7 return function() {
8 var context = this, args = arguments;
9 var later = function() {
10 timeout = null;
11 if (!immediate) func.apply(context, args);
12 };
13 var callNow = immediate && !timeout;
14 clearTimeout(timeout);
15 timeout = setTimeout(later, wait);
16 if (callNow) func.apply(context, args);
17 };
18};
19
20// Usage:
21var myEfficientFn = debounce(function() {
22 // All the taxing stuff you do
23}, 250);
24
25window.addEventListener('resize', myEfficientFn);
1
2// This is from David Walshes Blog Post
3// https://davidwalsh.name/javascript-debounce-function
4// A very simplified but effective version of Underscores debounce function
5function debounce(func, wait, immediate) {
6 var timeout;
7 return function() {
8 var context = this, args = arguments;
9 var later = function() {
10 timeout = null;
11 if (!immediate) func.apply(context, args);
12 };
13 var callNow = immediate && !timeout;
14 clearTimeout(timeout);
15 timeout = setTimeout(later, wait);
16 if (callNow) func.apply(context, args);
17 };
18};
1function debounce(func, timeout = 300){
2 let timer;
3 return (...args) => {
4 clearTimeout(timer);
5 timer = setTimeout(() => { func.apply(this, args); }, timeout);
6 };
7}
8function saveInput(){
9 console.log('Saving data');
10}
11const processChange = debounce(() => saveInput());