函数节流与函数防抖

函数节流与防抖是很相似的概念,但它们的应用场景不太一样。

函数节流

  • 定义:指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。
  • 应用场景:
    • 用于监听 mousemove, touchmove, resize, scroll等事件
    • 拖拽动画、下拉加载等
    function throttle(fn, delay = 200){
      var lastTime = 0;
      return function(){
        var nowTime = new Date();
        if(nowTime - lastTime > delay){
          fn.call(this)
          lastTime = nowTime
        }
      }
    }
    
    document.onscroll = throttle(function(){
      console.log("e")
    })

函数防抖

  • 定义:指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
  • 应用场景:
    • 可用于input.change实时输入校验,比如输入实时查询,你不可能摁一个字就去后端查一次,肯定是输一串,统一去查询一次数据
    • 提交按钮的点击事件
   <button>提交</button>

   /****非立即执行******/
   function debounce(fn, delay = 1000){
      var timer = null;
      return function(){
        clearTimeout(timer);
        timer = setTimeout(function(){
          fn.apply(this)
        }, delay)
      }
    }
    
    /****立即执行******/
    function debounce(fn, delay = 1000){
      var timer = null;
      return function(){
        clearTimeout(timer);
        if(!timer){
          fn.apply(this)
        }
        timer = setTimeout(function(){
          timer = null
        }, delay)
      }
    }
    
    document.querySelector('input').onclick = debounce(function(){
      console.log("触发了")
    })
原文地址:https://www.cnblogs.com/vicky123/p/14016442.html