防抖函数 要求:
当持续触发事件,一定时间内没有再触发事件,事件处理函数才会再执行一次*
当设定的事件来到之前,有一次触发了事件,就重新开始延时
代码的详细讲解
var input = document.querySelector('#input')
function debounce(delay) {
let timer
return function (value) {
clearTimeout(timer)
timer = setTimeout(() => {
console.log(value);
}, delay)
}
}
var debouncefunc = debounce(1000)
input.addEventListener('keyup', (e) => {
debouncefunc(e.target.value)
})
完整代码
<!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>
<input type="text" id="input">
<script>
var input = document.querySelector('#input')
function debounce(delay) {
let timer
return function (value) {
clearTimeout(timer)
timer = setTimeout(() => {
console.log(value);
}, delay)
}
}
var debouncefunc = debounce(1000)
input.addEventListener('keyup', (e) => {
debouncefunc(e.target.value)
})
</script>
</body>
</html>
|