- 防抖
防抖:多次触发事件,只取最后一次,在最后一次触发后执行事件函数
function debounce(fun,wait){
var timeout = null;
return function(){
clearTimeout(timeout);
timeout=setTimeout(fun,wait);
}
}
function method(){
console.log("防抖");
}
window.onscroll=debounce(method,500);
- 节流
节流:在触发事件的过程中,每隔一定时间间隔执行对应的事件处理函数
function throttle(fun,wait) {
var _this = this;
var arg = arguments;
var time = null;
return function () {
if (!time) {
time = setTimeout(function () {
time = null;
fun.apply(_this,arg);
}, wait)
}
}
}
function method(){
console.log("节流");
}
window.onscroll=throttle(method,500);