防抖debounce:当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次。
function debounce(method, context) {
clearTimeout(method.tId)
method.tId = setTimeout(function() {
method.call(context)
}, 100)
}
function resize() {
console.log("xxx")
}
window.onresize = function() {
debounce(resize)
}
节流throttle:当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
const throttle = function(func, delay) {
var prev = Date.now();
return function() {
var now = Date.now();
if(now - prev >= delay) {
func.apply(this);
prev = Date.now();
}
}
}
function handle() {
console.log('xxx');
}
window.addEventListener('scroll', throttle(handle, 5000));