Skip to main content

节流

function throttle(func, wait) {
let timeout,self,args;
let previous = 0;
let later = function(){
previous = +new Date();
timeout = null;
func.apply(self,args);
}
let throttled = function(...param) {
self = this;
args = param;
let now = +new Date();
let remaining = wait-(now-previous);
// 如果没有剩余的时间了或者你改了系统时间
if (remaining<=0 || remaining>wait) {
if(timeout){
clearTimeout(timeout)
timeout=null;
}
previous = now;
func.apply(self, args);
}else if(!timeout){
timeout=setTimeout(later,remaining);
}
};
return throttled;
}
window.addEventListener('scroll',throttle(fn,500));