码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript 防抖(debounce)和节流(throttle)

时间:2020-07-22 02:10:29      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:efi   demo   asc   The   eset   timeout   ram   cut   tle   

防抖函数

/**
 *
 * @param {*} fn :callback function
 * @param {*} duration :duration time,default wait time 0.8 秒
 * @demo in vue methods:
 *      handleEvent: _debounce(function(){
 *        do something
 *      },time)
 */
export const _debounce = (fn, duration = 800) => {
  // create timer
  let timer = null
  return function () {
    // reset once call
    clearTimeout(timer)
    // create a new timer to make sure call after define time
    timer = setTimeout(() => {
      // execute callbak, the 2nd params is fn‘s arguments
      fn.apply(this, arguments)
    }, duration)
  }
}

节流函数

/**
 * @param {*} fn: callback function
 * @param {*} duration : duration time,default wait time 1 sec
 * @demo in vue methods:
 *      handleEvent: _throttle(function(){
 *        do something
 *      },time)
 */
export const _throttle = (fn, duration = 1000) => {
  let canRun = true
  return function () {
    if (!canRun) return
    canRun = false
    // execute callbak, the 2nd params is fn‘s arguments
    fn.apply(this, arguments)
    setTimeout(() => {
      canRun = true
    }, duration)
  }
}

JavaScript 防抖(debounce)和节流(throttle)

标签:efi   demo   asc   The   eset   timeout   ram   cut   tle   

原文地址:https://www.cnblogs.com/leslie1943/p/13358084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!