防抖 是 防抖deounce
节流 是 节流 throttle
防抖:
小明军训,教官发令:向左转!向右转!向后转!大家都照着做,唯有小明坐下来休息,教官火的一批,大声斥问他为啥不听指挥?小明说,我准备等你想好到底往哪个方向转,我再转。
只有教官最后一次发号后,小明才会转。
相当于vue中的修饰符lazy 的效果
可用于input.change实时输入校验,比如输入实时查询,你不可能摁一个字就去后端查一次,肯定是输一串,统一去查询一次数据。
可用于 window.resize 事件,比如窗口缩放完成后,才会重新计算部分 DOM 尺寸
<!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>
<input type="text" id="ipt">
</body>
</html>
<script>
let ipt = document.querySelector('#ipt')
//核心代码
function deboounce(fn, delay) {
let timer
//为了实现防抖的效果
//我们采用定时器的方法
//但为了能够清楚定时器
//我采用 声明变量的方法 且 闭包的形式 来保存定时器 以至于 后面再清除的时候 能够成功的清除
return function (value) {
clearTimeout(timer)
timer = setTimeout(() => {
fn(value) //我们原先是在这里 进行打印的 现在我们封装成了函数
}, delay);
}
}
function setTime(value) {
console.log(value);
}
var deboounceFn = deboounce(setTime, 1000)
ipt.addEventListener('keyup', (e) => {
deboounceFn(e.target.value)
})
</script>
节流:
学生上自习课,班主任五分钟过来巡视一次,五分钟内随便你怎么皮,房顶掀了都没事,只要你别在五分钟的时间间隔点上被班主任逮到,逮不到就当没发生,逮到她就要弄你了。
用于监听 mousemove、 鼠标滚动等事件,通常可用于:拖拽动画、下拉加载。
<!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>
<button id="a">点击</button>
</body>
</html>
<script>
//实现节流
function thro(func, time) {
let timerOut;
// console.log(func, time);
//我们要做到的是 当timerOut不存在时执行下面的函数
//当timerOut 存在的时候不执行
return function () {
// console.log(func, time);
if (!timerOut) {
timerOut = setTimeout(() => {
func()
timerOut = null
}, time)
}
}
}
function handle() {
console.log(Math.random());
}
document.getElementById('a').onclick = thro(handle, 2000)
</script>