今天复习一下js中的防抖与节流。
一、防抖:用户触发过于频繁,只要最后一次事件操作
1、代码展示
<style>
body{
height:2000px;
}
</style>
<input type="text">
<script>
let inp = document.querySelector("input");
inp.oninput = function(){
console.log(this.value)
}
</script>
2、问题场景:当我们往输入框输入数据的时候,每输入一次的时候控制台就会打印一次,但是我们想的是当输入最后一个字母的时候才会打印出来,这就是我们要解决的防抖
3、最简单的防抖,但是防抖代码和业务代码放在了一起,并且还有全局变量,因此极不推荐这样写
<style>
body{
height:2000px;
}
</style>
<input type="text">
<script>
let inp = document.queySelector("input"); //先获取到该标签
let t = null;
inp.oninput = function(){ //通过oninput来向标签中添加数据
if( t !=null){ //若不是最后一次事件的操作有数据的输入则清除
clearTimeout(t)
}
//最后一次执行事件操作
t = setTimeout( () => {
console.log( this.value)
},500)
}
</script>
4、为了解决上面的问题因此可以通过使用闭包来实现对防抖的封装
<style>
body{
height:2000px;
}
</style>
<input type="text">
<script>
let inp = document.querySelector("input");
inp.document = debounce( function(){
console.log(this.value)
},500)
//利用闭包封装
function debounce(fn,delay){
let t = null;
return function(){
if( t != null){
clearTimeout(t);
}
t = setTimeout( () => {
fn.call(this)
},delay)
}
}
</script>
二、节流:控制高频事件的触发,比如我们下拉滑动块的时候事件的频繁触发
1、最基本的节流,同样问题很多,不提倡使用
<style>
body{
height:2000px;
}
</style>
<input type="text">
let flag = true;
window.onscroll = function(){
console.log("hello world");
if(flag){
setTimeout( ()=>{
console.log("hello world");
flag = true;
},1000 )
}
flag = false;
}
2、通过闭包来实现对节流的封装
<style>
body{
height:2000px;
}
</style>
<input type="text">
<script>
window.onscroll = throttle(function(){
console.log("hello world")
},500)
//利用闭包封装
function throttle(fn,delay){
let flag = true;
return function(){
if(flag){
setTimeout( () =>{
fn.call(this);
flag = true;
},delay)
}
flag = false;
}
}
</script>