防抖和节流
定义
- 防抖:n秒后再执行该事件。若在n秒内被重复触发,则重新计时
- 节流:n秒内只运行一次。若在n秒内重复触发,只有一次生效(最后一次生效)
运用场景
-
防抖
- 输入框搜索,进行请求
- 邮件输入验证
- 窗口resize
-
节流
- 滚动加载
核心代码
防抖
/*
第一个参数:防抖处理函数
第二个参数:延迟时间,默认1秒钟
*/
function debounce(fn, delay = 1000) {
// 实现防抖函数的核心是使用setTimeout
let timer = null; // 记录setTimeout返回的id
return function() {
// 定时器存在,清除
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
/*
改变this的指向,指向外部传进来的fn
同时将参数传递给fn
*/
fn.call(this, args)
}, delay)
}
}
例子
- 防抖
<input type="text" id="input"/>
<script>
const inputNode = document.querySelector('#input')
inputNode.addEventListener('keyup', debounce((e) => {
console.log(`点击了,输入的值是${e[0].target.value}`);
}))
function debounce(fn, delay = 1000) {
let timer = null;
return function() {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.call(this, arguments)
}, delay)
}
}
</script>
节流
function throttle(fn, delay) {
let timer = null;
return function() {
if (timer) return;
timer = setTimeout(() => {
fn.call(this, arguments)
timer = null;
}, delay)
}
}