From

函数节流:常用于onresize,scroll,mousemove,mousehover等连续触发的事件(隔断时间触发一次)。

方法:

eg.
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
	window.onscroll = function() {
console.log('scoll滑动');
throttle(count);
};

function count() {
console.log('函数调用');
}

function throttle(method, context) {
// 如果连续触发就会方法会被清除,所以只会执行最后一次
clearTimeout(method.tId);
method.tId = setTimeout(function() {
method.call(context);
}, 300);
}

// eg.
var time = +new Date(); // 隐式转换,相当于new Date().getTime()
function count() {
console.log('函数调用:' + (+new Date() - time));
}


// 到达mustRun毫秒一定执行
var throttle = function(fn, delay, mustRun) {
var timer = null,
previous = null;

return function() {
var now = +new Date(),
context = this,
args = arguments;
// 闭包,只有在第一次执行时,previous==null,会被赋值为now
if(!previous) previous = now;
var remaining = now - previous;
if(mustRun && remaining >= mustRun){
fn.apply(context, args);
previous = now;
} else {
cleaerTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
}
};
};

window.onscroll = throttle(count, 500, 1000);