防抖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
function debounce(fn, delay) {
// 1. 定义一个定时器变量
var timer
// 2. 返回回调函数
return function () {
// 3. 每次执行都清空定时器
clearTimeout(timer)
// 4. 重新定时
timer = setTimeout(() => {
fn()
}, delay)
}
}
function handleFn() {
console.log('success')
}
// 没采用防抖
window.addEventListener('mousemove', handleFn)
// 采用了防抖 控制了触发频率 一段时间内无操作才会触发事件 否则就会再次计时
window.addEventListener('mousemove', debounce(handleFn, 1000))
</script>
</body>
</html>
节流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
function throttle(fn, delay) {
// 定义一个定时器
var timer
// 返回回调函数
return function () {
// 判断定时器为假才执行函数
if (!timer) {
timer = setTimeout(() => {
fn()
// 执行之后 清空定时器
timer = null
}, delay)
}
}
}
function handleFn() {
console.log('success')
}
// 采用了节流 每隔一秒才会触发一次事件,控制了事件触发频率
window.addEventListener('mousemove', throttle(handleFn, 1000))
</script>
</body>
</html>