防抖節(jié)流函數(shù)

前沿: 僅作為筆記記錄,持續(xù)更新

一。首次學習(參考
  1. 防抖,防止持續(xù)操作,如點擊事件等
    原理:固定時間只能操作一次
    思路:每次點擊的時候讓它把之前的定時器清空,最終只執(zhí)行當前的操作。
  2. 節(jié)流,防止持續(xù)輸出,如鼠標移動事件持續(xù)移動、瀏覽器窗口變化持續(xù)打印等
    原理:固定時間只會輸出一次
    思路:每幾秒時候再執(zhí)行,最終一定時間只會執(zhí)行一次。
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Document</title>
</head>
<body>
   <div> 
      <button id="debounce">debounce</button>
      <button id="throttle">throttle</button>      
      
   </div>
</body>
</html>
<script>
   const debounce = (fn, delay) => {
      let timer = null
      return function(){
          if(timer){
             clearTimeout(timer)
          }
          timer = setTimeout(fn, delay)
      }
   }

   const throttle = (fn, delay) => {
      let flag = true
      return function (){
         if(!flag){
            return false
         }
         flag = false
         setTimeout(() => {
            flag = true
            fn()
         },delay)
      }
   }

   const deDothing = () => {
      console.log('debounce')
   }
   const thDothing = () => {
      console.log('throttle')
   }   

   const debounceDom = document.getElementById('debounce')
   debounceDom.onclick = debounce(deDothing, 1000)

   const throttleDom = document.getElementById('throttle')
   throttleDom.onclick = throttle(thDothing, 1000)
</script>
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容