防抖:输入框输入搜索,减少输入中没有必要的http请求
function debounce (func, wait) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(this, arguments);
}, wait);
}
}
window.onscroll = debounce(() => {
console.log(document.documentElement.scrollTop);
}, 1000);
节流:在规定的时间中只触发一次,就像水滴一样
function throttle (func, delay) {
let preTime = Date.now();
return function () {
let curTime = Date.now();
if (curTime - preTime > delay) {
func.apply(this, arguments);
preTime = curTime;
}
}
}
window.onscroll = throttle(() => {
console.log('throttle');
}, 1000);