-
Notifications
You must be signed in to change notification settings - Fork 5
/
throttle_debounce.js
55 lines (51 loc) · 1.11 KB
/
throttle_debounce.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
/**
* 函数防抖
* @param {*} fn
* @param {ms} delay
*/
function debounce(fn ,delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if(timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function(){
fn.apply(context, args);
},delay)
}
}
var fn = function(){
console.log(new Date()+'time');
}
setInterval(debounce(fn, 500),1000)
/**
* 函数节流
* @param {*} fn
* @param {*} gaptime
*/
function throttle(fn, gaptime) {
var timer;
var last;
return function() {
var now = +new Date();
var context = this;
var args = arguments;
if(last && now < last + gaptime) {
clearTimeout(timer);
timer = setTimeout(function(){
last = now;
fn.apply(context, args);
}, gaptime)
}else {
last = now;
fn.apply(context, args);
}
}
}
var fn = function(){
console.log('hello' + new Date())
}
setInterval(throttle(fn, 2000), 1000)