防抖(debounce)
就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
举例:监听一个输入框的内容,文字变化后触发change事件,直接使用keyup事件,则会频繁触发change事件,
使用防抖函数,用户输入结束或暂停时,才会触发change事件。
<input type="text" id="input1" />
input1.addEventListener("keyup",debounce(() => {console.log(inpu1.value);}));function debounce(fn, delay = 500) {let timer = null; // 闭包return function () {if (timer) {clearTimeout(timer);}timer = setTimeout(() => {fn.apply(this, arguments);timer = null;}, delay);};}
节流(throttle)
就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。
举例:拖拽一个元素,要随时拿到该元素被拖拽的位置,直接用drag事件,则会频繁触发,很容易造成卡顿,
使用节流函数,无论拖拽速度多快, 都会每隔100ms触发一次。
<style>#div1 {width: 200px;height: 100px;border: 1px solid #ccc;}</style><div id="div1" draggable="true">拖拽</div>
div1.addEventListener("drag", throttle((e) => {console.log(e.offsetX, e.offsetY);}));function throttle(fn, delay = 100) {let timer = null;return function () {if (timer) return;timer = setTimeout(() => {fn.apply(this, arguments);timer = null;}, delay);};}
