节流:当持续触发事件时,一段时间内只调用一次处理函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="button">BUTTON</button>
<script>
function thro(func, wait) {
let timerOut
return () => {
if (!timerOut) {
timerOut = setTimeout(()=>{
func()
timerOut = null
}, wait)
}
}
}
function handle() {
console.log(Math.random())
}
let btnObj = document.getElementById('button')
btnObj.onclick = thro(handle, 2000)
</script>
</body>
</html>
防抖:当持续触发事件,一定时间内没有再触发事件,事件处理函数才会执行一次,如果没有到设定时间到之前,又触发了事件,就重新开始延时
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="input">
<script>
let inputo = document.getElementById('input')
function debounce(callback, delay) {
let timer
return function(arg) {
clearTimeout(timer)
timer = setTimeout(()=>{
console.log(arg)
}, delay)
}
}
function func(value) {
console.log(value)
}
let debounceFn = debounce(func, 1000)
inputo.addEventListener('keyup', (e)=>{
debounceFn(e.target.value)
})
</script>
</body>
</html>
本文通过示例代码详细介绍了JavaScript中的事件处理函数优化技术——节流和防抖。节流(throttle)用于限制函数在一定时间内的调用频率,而防抖(debounce)则是确保在事件触发的间隔结束后才执行函数。这两种技术常用于提升性能,例如在滚动事件、输入事件等场景中。
1501

被折叠的 条评论
为什么被折叠?



