-
Notifications
You must be signed in to change notification settings - Fork 1
/
debounce_throttle.js
70 lines (52 loc) · 1.1 KB
/
debounce_throttle.js
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
let i=0
console.log(i)
setInterval(()=>{console.log(++i)}, 1000)
function debounce(f, delay) {
var timer
return function() {
let context = this
let args = arguments
clearTimeout(timer)
timer = null
timer = setTimeout( ()=>{
clearTimeout(timer)
timer = null
f.apply(context, args)
}, delay )
}
}
/*
f = (name) => console.log('f called, ' + name)
ff = debounce(f, 2000)
ff('11111')
setTimeout(ff, 1000, '22222')
setTimeout(ff, 2000, '33333')
setTimeout(ff, 3000, '44444')
setTimeout(ff, 4000, '55555')
setTimeout(ff, 5000, '66666')
*/
function throttle(f, interval) {
var timer
return function() {
let context = this
let args = arguments
if (timer) return;
timer = setTimeout( ()=>{
clearTimeout(timer)
timer = null
f.apply(context, args)
}, interval )
}
}
//*
f = (name) => console.log('f called, ' + name)
ff = throttle(f, 2000)
ff('11111')
setTimeout(ff, 1000, '22222')
setTimeout(ff, 2000, '33333')
setTimeout(ff, 3000, '44444')
setTimeout(ff, 4000, '55555')
setTimeout(ff, 5000, '66666')
setTimeout(ff, 6000, '77777')
setTimeout(ff, 7000, '88888')
//*/