防抖函數
防抖是防止連續觸發事件,只觸發最后一次事件,可以使用防抖函數。
簡單例子
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 }
浙公網安備 33010602011771號