函数节流的目的:防止不是用用户直接控制的函数,频繁触发
函数频繁被调用的场景:window.onresize,mousemove
函数节流的代码实现(经典案例):
var throttle = function(fn,interval) {
var self = fn,timer,firstTime = true;
return function() {
var args = arguments,_this = this;
if(firstTime) {
self.apply(_this,args);
return firstTime = false;
}
if(timer) {
return false
}
timer = setTimeout(function() {
clearTimeout(timer);
self.apply(_this,args);
},interval||500)
}
}
window.onresize = throttle(function() {console.log(1)},500)