防抖
当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时
场景:暴力点击,输入获取
const delay = (function () {
let timer = 0
return function (callback, ms) {
clearTimeout(timer)
timer = setTimeout(callback, ms)
}
})()
节流
当持续触发事件时,保证一定时间段内只调用一次事件处理函数
场景:检测高度 懒加载
var throttle = function(func, delay) { var timer = null; return function() { var context = this; var args = arguments; if (!timer) { timer = setTimeout(function() { func.apply(context, args); timer = null; }, delay); } } } function handle() { console.log(Math.random()); } window.addEventListener(‘scroll‘, throttle(handle, 1000));
这是简单版的demo,懂其含义 然后就可以根据自己得需求去做相应得改变了
debounce的特点是当事件快速连续不断触发时,动作只会执行一次。 延迟debounce,是在周期结束时执行,前缘debounce,是在周期开始时执行。但当触发有间断,且间断大于我们设定的时间间隔时,动作就会有多次执行。
原文:https://www.cnblogs.com/helow/p/14131010.html