小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
防抖和节流
防抖
防抖就是在触发事件n秒后才执行,如果n秒内重复触发了事件,则重新计时。
防抖的实现又分为立即执行版和非立即执行版。立即执行版指触发事件后函数会立即执行,然后 n 秒内不触发事件才能继续执行函数的效果。
非立即执行指触发事件后函数不会立即执行,而是在 n 秒后执行,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
立即执行版实现:
function debounce(func,wait) {
let timeout;
return function () {
const context = this;
const args = [...arguments];
if (timeout) clearTimeout(timeout);
const callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
}
非立即执行版实现:
function debounce(func, wait) {
let timeout;
return function () {
const context = this;
const args = [...arguments];
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
实际应用:
-
监听input框的oninput事件时,使用防抖来节约资源。
-
监听页面的resize事件时
节流
节流是指在不断的触发事件中,事件在n秒内只会执行一次。比如:你不断的点击鼠标,事件只会n秒执行一次。
节流实现:
function throttle(fn, delay) {
let timer = null;
return function () {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(function () {
fn.apply(context, args);
timer = null;
}, delay);
}
}
}
实际应用:
- scroll事件,每隔1s才计算一次位置信息,避免边滚动边计算