Skip to content

Commit b15cae1

Browse files
committed
adds debounce events page
1 parent 18ab036 commit b15cae1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/javascript/debounce-events.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
A debounced function is run after a defined delay.
2+
3+
The function below has two parameters:
4+
5+
- passedFunction: the function normally given to eventListeners to run.
6+
- Can be an anonymous function e.g. function() {...}
7+
- delay: amount of time to wait before firing function
8+
- Defaults to 200ms
9+
10+
```js
11+
function debounced(passedFunction, delay = 200) {
12+
let timerId;
13+
14+
//return function with arguments from passed function
15+
return function(...args) {
16+
//if timerid exists, clear it and start a new one
17+
if (timerId) {
18+
clearTimeout(timerId);
19+
}
20+
21+
//since timerId is always unset, we must set it
22+
timerId = setTimeout(() => {
23+
//run passedFunction with ...args
24+
passedFunction(...args);
25+
26+
//unset timerId
27+
timerId = null;
28+
29+
//wait this long before you fire this function
30+
}, delay);
31+
};
32+
}
33+
```
34+
35+
Based off of [this article](https://codeburst.io/throttling-and-debouncing-in-javascript-646d076d0a44)

0 commit comments

Comments
 (0)