例如:输入,点击,移动,键盘,滚动条。。。。
防抖
1.使用别人写好的(jq $,lodash _)
lodash文档:lodash.debounce | Lodash中文文档 | Lodash中文网
2.自己写
<input type="text" id="inp">
<script>
let inp =document.getElementById("inp")
let count = 0
let search=function(e){
count++
console.log(count)
}
inp.oninput=myDebounce(search,1000)
function myDebounce(search,time){
let timer=''
return function(e){
clearTimeout(timer)
let t=this
timer=setTimeout(()=>{
search.call(t,e)
},time)
}
}
</script>
核心思路:用定时器对防抖内容做延时,在下次触发的时候,先清除上次延迟
节流
1.使用别人写好的(jq $,lodash _)
lodash文档:lodash.throttle | Lodash中文文档 | Lodash中文网
2.自己写
<input type="text" id="inp">
<script>
let inp =document.getElementById("inp")
let count = 0
let search=function(e){
count++
console.log(count)
}
inp.oninput=myDebounce(search,1000)
function myDebounce(search,time){
let ctime=0
return function(e){
let etime=new Date().getTime()
if(etime-ctime>=time){
search.apply(this,[e])
ctime=etime
}
}
}
</script>