话不多说直接上代码:
js函数防抖:多次触发事件,只有最后一次执行
function debounce(cb, delay){
var t = null;
return function () {
clearTimeout(t);
t = setTimeout(cb , delay)
}
}
window.onscroll = debounce(function (){
console.log(1); // 滚动事件完成500毫秒之后执行1次输出1
},500)
js函数节流:多次触发事件,单位时间内只执行一次
function throttle (cb, delay) {
var lastTime = new Date().getTime();
return function () {
var now = new Date().getTime();
if (now - lastTime > delay) {
cb();
lastTime = now;
}
}
}
window.onscroll = throttle(function (){
console.log(1); // 滚动的时候,每隔500毫秒输出1次1
},500)