「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」。
防抖
概念
事件被触发n
秒后执行,如果在n
秒内又触发,则重新计时
使用场景 电商网站搜索框、后台管理数据搜索
实现思路
- 使用定时器
- 触发事件前,清楚上一次遗留的定时器,保证只执行一次
<!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>实现防抖</title>
</head>
<body>
<script>
function debounce(func, interval) {
let timer
return (arguments) => {
clearTimeout(timer) // 清楚上一个定时器,保证n秒后执行
timer = setTimeout(() => func(arguments), interval)
}
}
window.onresize = debounce(function (event) {
console.log(event)
}, 1000)
</script>
</body>
</html>
节流
概念 规定在一定的单位时间内,事件只会触发一次。如果在单位时间内多次触发,只会响应一次。
使用场景
一般用在scroll
、resize
、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>实现节流</title>
</head>
<body>
<script>
// 每隔固定的时间触发
function throttle(fn, interval) {
let timer
return (arguments) => {
if (!timer) { // 如果规定时间内多次触发,只会执行一次
timer = setTimeout(() => {
clearTimeout(timer)
timer = null
fn(arguments)
}, interval)
}
}
}
window.onresize = throttle(function (event) {
console.log(event, this)
}, 1000)
</script>
</body>
</html>