节流:当持续触发事件时,一段时间内只调用一次处理函数
<!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>