Simple Implementation of Throttle and Debounce

Simple Implementation of Throttle and Debounce

August 24, 2018

Throttle and Debounce

In front-end, throttle and debounce are quite important for performance enhancement. Especially useful on events like window.onresize which will be triggered in high frequency.

I have just put a very very simple implementation underneath.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function debounce(func, wait) {
var timer = null;

return function (){
var self = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function (){
func();
}, wait);
}
}


function throttle (action, delay) {
var startTime = 0;

return function (){
var currentTime = new Date();

if (currentTime - startTime > delay) {
action.apply(this, arguments);
startTime = currentTime;
}
}
}