Debounce

The goal of the debounce function is to prevent execution of the same code several times in succession, which typically happens with the code bound to resize and scroll events.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}

source

Share