节流
// 节流,规定时间内只触发一次,类似于游戏中技能释放
<style>
body{
height: 2000px;
}
</style>
window.onscroll=throttle(function(){ console.log('123');},500)
function throttle( fn, delay){
let flag=true
return function(){
if(flag){
setTimeout(()=>{
fn.call(this) //call绑定this ,
flag=true
},delay)
}
flag=false
}
}
//一开始flag为true, 直接走定时器,执行完之后,flag为false, 相当于把fn 执行函数控制在规定时间内执行,但只能执行一次,所以要在里面把flag 改为true, 才能循环走下去
防抖
// 防抖,频繁触发,只执行一次, 类似于游戏回城,
<input type="text">
let inp=document.getElementsByTagName('input')[0]
inp.oninput=debounce(function(){ console.log(this.value);}, 500)
function debounce( fn ,delay){
let t=null
return function(){
if(t!==null){
clearTimeout(t) //一开始t为空,开始一个定时器,定时器没有走完,如果再开启,直接就清除,这就是防抖的效果
}
t=setTimeout(() => {
fn.call(this) //绑定this
}, delay);
}
}