Skip to content

Commit 9ae5223

Browse files
.
1 parent 4de0604 commit 9ae5223

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

util/debounce/.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
The debounce function can be a game-changer when it comes to event-fueled performance. If you aren't using a debouncing function with a scroll, resize, key\* event, you're probably doing it wrong. Here's a debounce function to keep your code efficient:

util/debounce/index.js

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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.
5+
function debounce(func, wait, immediate) {
6+
var timeout;
7+
return function () {
8+
var context = this,
9+
args = arguments;
10+
var later = function () {
11+
timeout = null;
12+
if (!immediate) func.apply(context, args);
13+
};
14+
var callNow = immediate && !timeout;
15+
clearTimeout(timeout);
16+
timeout = setTimeout(later, wait);
17+
if (callNow) func.apply(context, args);
18+
};
19+
}
20+
21+
// Usage
22+
var myEfficientFn = debounce(function () {
23+
// All the taxing stuff you do
24+
}, 250);
25+
26+
window.addEventListener("resize", myEfficientFn);
27+
// The debounce function will not allow a callback to be used more than once per given time frame. This is especially important when assigning a callback function to frequently-firing events.

0 commit comments

Comments
 (0)