<!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>Document</title>
<style>
</style>
</head>
<body>
<input type="text">
<script>
let input=document.querySelector("input");
input.addEventListener('input',function(){
console.log(this.value)
})
</script>
</body>
</html>
用 time 来控制事件的触发,然后建立一个延时器,用固定事件500ms来控制事件的触发,输出this.value ,那么之前,需要进行一个判断,判断time是不是有值,如果有值就去清掉time,然后下面的代码又重新赋值给time`。
<!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>Document</title>
<style>
</style>
</head>
<body>
<input type="text" placeholder="请输入">
<script>
let input=document.querySelector("input");
let time=null;
input.addEventListener('input',function(){
if(time!==null){
clearTimeout(time)
}
time=setTimeout(()=>{
console.log(this.value)
},500)
})
</script>
</body>
</html>
防抖优化
<!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>Document</title>
<style>
</style>
</head>
<body>
<input type="text">
<script>
let input = document.querySelector("input");
//input事件触发的时候,执行的是debounce返回的function,这个function里面有防抖和真正的业务逻辑
input.addEventListener('input', debounce(function () {
/*
用debounce函数去约束input这个事件,实际执行的函数是function函数,防抖的延迟是500ms
*/
console.log(this.value);//业务代码
}, 500));
//需要让debounce的返回值是一个函数
/*
fn : 回调函数 传进来的是正真的业务逻辑
delay : 延时时间
*/
function debounce(fn, delay) {
let time = null;//time用来控制事件的触发
return function () {
if (time !== null) {
clearTimeout(time);
}
time = setTimeout(() => {
fn.call(this);
//利用call(),让this的指针从指向window 转成指向input
}, delay)
}
}
</script>
</body>
</html>