在界面触发点击,滚动,输入校验等事件时,如果对事件的触发频率不加以限制,会给浏览器增加负担,且对用户不友好。防抖和节流就是针对类似情况的解决方案。
防抖
防抖(debounce):当连续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><div>点击<span class="count">0</span>次</div><button class="button">button</button><script>let count = 0;function debounce(fn, await) {let timer = null;return function(...args) {if(timer) clearTimeout(timer);timer = setTimeout(() => fn.apply(this, args), await);}}function calCount() {const ele = document.getElementsByClassName('count')[0];count++;ele.innerHTML = count;}const btn = document.getElementsByClassName('button')[0];btn.addEventListener('click', debounce(calCount, 1000));</script>
</body>
</html>
节流
节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。
示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><div>点击<span class="count">0</span>次</div><button class="button">button</button><script>let count = 0;function throttle(fn, await) {let preTime = Date.now();return function(...args) {let now = Date.now();if(now - preTime >= await) {fn.apply(this, args);preTime = Date.now();}}}function calCount() {const ele = document.getElementsByClassName('count')[0];count++;ele.innerHTML = count;}const btn = document.getElementsByClassName('button')[0];btn.addEventListener('click', throttle(calCount, 1000));</script>
</body>
</html>