防抖函数

防抖是防止连续触发事件,只触发最后一次事件,可以使用防抖函数。

简单例子

 1             let oinput=document.querySelector('input')
 2             let t=null;
 3             oinput.oninput=function(e){
 4     
 5                 if(t!==null) {
 6                     clearTimeout(t)
 7                 }
 8                 t=setTimeout(()=>{
 9                     console.log(this.value)
10                 },1000)
11                 
12             }

最后封装的例子

 1             let oinput=document.querySelector('input')
 2             oinput.oninput=debounce(function(){
 3                 console.log(this.value)
 4             },1000)
 5             
 6             function debounce(fn,delay) {
 7                 let t=null;
 8                 return function(){
 9                     if(t!==null) {
10                         clearTimeout(t)
11                     }
12                     t=setTimeout(()=>{
13                         fn.call(this)
14                     },delay)
15                 }
16             }

 

posted @ 2023-07-18 12:20  font-dev  阅读(39)  评论(0编辑  收藏  举报