防抖
-
概念
假定时间间隔为200ms,如果触发事件后的200ms内再次触发事件,则重新等待200ms,否则将成功执行指定函数。 -
应用场景
数据查询、监控用户输入 -
代码实现
function search() { var t = null; // 使用闭包 return function () { if (t) { clearTimeout(t); t = null } t = setTimeout(() => { console.log('执行啦'); t = null; }, 2000); } } var test1 = document.getElementById('test2'); test1.onclick = search();
节流
-
概念
连续触发事件,只在指定时间间隔执行指定函数。 -
应用场景
页面自适应、监控页面滚动、鼠标移动 -
代码实现
// 方法一:首次立即触发 function throttle1(fn, interval) { let open = true let first = true return function () { if (!open) { return } open = false // !!!!!! 首次立刻执行 if (first) { console.log('首次触发') fn() first = false } const now = Date.now() const wait = now % interval setTimeout(() => { fn() open = true }, interval - wait) } } // 方法二:首次立即触发,间隔时间更稳定 function throttle2(fn, interval) { let lastTime = 0 let timer = null return function () { const context = this const args = arguments const curTime = Date.now() const duration = interval - (curTime - lastTime) clearTimeout(timer) if (duration <= 0) { fn(args) lastTime = curTime } else { timer = setTimeout(function () { fn.apply(context, args) lastTime = lastTime + interval }, duration) } } } // 测试代码 let times = 0 let onMouseMove = throttle2(() => { console.log(new Date().getTime(), times) }, 10) let i = setInterval(() => { if (times++ === 1000) { clearInterval(i) } onMouseMove() }, 1)