节流函数及其应用

建议使用 lodash 插件里面的 throttle 函数来实现

1、节流函数简单原理

/**
 * 节流函数
 * 定义:指连续触发事件但是在 n 秒中只执行一次函数(第一次)
 * 作用:节流会稀释函数的执行频率
 * param1、param2 为额外定制接受的参数
 */
function throttle (fn, delay, param1 = '', param2 = '') {
  /* 获取接收的参数,排除掉前两位固定的参数 */
  const params = [...arguments].splice(2)
  /* 用户执行时的时间,初始值为 0 */
  let clickTime = 0
  return function () {
    /* 用户执行时的时间戳 */
    const now = Date.now()
    /* 若用户执行时的时间戳 - 用户执行时的时间 > 规定时间  */
    if (now - clickTime > delay) {
      /* 执行函数,并将参数设置到函数的 arguments 对象中 */
      fn.call(this, ...params)
      /* 将用户执行时的时间戳赋值给用户执行时的时间 */
      clickTime = now
    }
  }
}

2、节流函数的应用

/**
 * 某个元素点击要执行的事件
 * 假设要对这个事件进行节流
 */
function task (params = 'params') {
  console.log(1, params);
}

/**
 * 节流函数的应用
 */
$('.dom').on('click', throttle(task, 1000, 'hehe'))

你可能感兴趣的:(节流函数及其应用)