美文网首页
debounce和throttle

debounce和throttle

作者: 脆脆鲨765 | 来源:发表于2020-11-16 15:45 被阅读0次
    // 常用于window resize 或 scroll监听
    function debounce(fn, wait) {
      wait = wait || 0
      let timerId
    
      return function () {
        let context = this
        let args = arguments
    
        if (timerId) {
          clearTimeout(timerId)
    
          timerId = null
        }
        timerId = setTimeout(function () {
          fn.apply(context, args)
        }, wait)
      }
    }
    
    // 常用于按钮提交 或 实时查询
    function throttle(fn, threshhold) {
      let last, timer
      threshhold || (threshhold = 200)
    
      return function () {
        let context = this
        let args = arguments
    
        let now = +new Date()
    
        if ((last && now < last + threshhold)) {
          clearTimeout(timer)
    
          timer = setTimeout(function () {
            last = now
            fn.apply(context, args)
          }, threshhold)
        } else {
          last = now
          fn.apply(context, args)
        }
      }
    }
    

    相关文章

      网友评论

          本文标题:debounce和throttle

          本文链接:https://www.haomeiwen.com/subject/mbczbktx.html