防抖(Debouncing)和节流(Throttling)是两种常用于优化前端性能和用户体验的技术。它们都用于控制事件处理的频率,以避免不必要的触发。下面是防抖和节流的JavaScript示例:
防抖函数:
防抖的思想是,在事件触发后等待一段时间,如果在这段时间内没有再次触发事件,才执行事件处理函数。这对于处理例如搜索输入框的自动完成或者窗口大小调整等事件非常有用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖-debounce</title>
</head>
<body>
<button id="debounce">DEBOUNCE</button>
<script>
// 防抖思想:在时间触发一段时间后,若没有再次触发事件,则执行方法体
function debounce (func,delay){
// 定时器ID
let timer;
return function (){
// 清除定时器
clearTimeout(timer)
timer = setTimeout(()=>{
func.apply(this,arguments)
},delay)
}
}
// 测试
const handleDebounce = debounce(()=>{
console.log("debounce apply");
},2000)
document.getElementById("debounce").onclick = handleDebounce
</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>节流-throttle</title>
</head>
<body>
<button id="throttle">THROTTLE</button>
<script>
// 节流思想:在特定时间内,不管事件触发了多少次,只执行一次
function throttle (func,delay) {
// 定义一个标杆
let timer = false;
return function (){
// 根据标杆状态是否要执行函数
if(!timer){
func.apply(context,args)
timer = true;
setTimeout(()=>{
timer = false
},delay)
}
}
}
// 测试
const handleThrottle = throttle(()=>{
console.log("throttle apply");
},2000)
document.getElementById("throttle").onclick = handleThrottle
</script>
</body>
</html>