简易版节流与防抖函数封装

2021-04-01  本文已影响0人  莫伊剑客

定义

节流函数:将函数触发频率降低到可接受的范围内
防抖函数:高频多次调用同一个函数,只执行一次

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>节流与防抖</title>
</head>
<body>
<script>
/**
 * @file: index.html
 * @method throttle
 * @param {Function} fn - 回调函数
 * @param {Number} delay - 延时时间(毫秒)
 * @param {Boolean} start - 是否在节流前执行
 * @description: 节流函数,将函数触发频率降低到可接受的范围内,
 * @date: 2021/4/1
 */
function throttle(fn, delay = 200, start = true) {
  if (typeof fn !== 'function') {
    return console.error('必须传入一个函数')
  }
  let timer = 0
  return function (...arg) {
    // 定义指针变量
    const _this = this
    if (timer) return
    // 改变指针
    start && fn.apply(_this, arg)
    timer = setTimeout(function () {
      // 改变指针
      (!start) && fn.apply(_this, arg)
      timer = 0
    }, delay)
  }
}

/**
 * @file: index.html
 * @method debounce
 * @param {Function} fn - 回调函数
 * @param {Number} delay - 延时时间(毫秒)
 * @param {Boolean} start - 是否在防抖前执行
 * @description: 防抖函数:多次调用同一个函数,只执行一次
 * @date: 2021/4/1
 */

function debounce(fn, delay = 200, start = true) {
  if (typeof fn !== 'function') {
    return console.error('必须传入一个函数')
  }
  let timer = 0,
    isFirst = true
  return function (...arg) {
    const _this = this
    clearTimeout(timer)
    if (isFirst && start) {
      fn.apply(_this, arg)
      isFirst = false
    }
    timer = setTimeout(function () {
      (!start) && fn.apply(_this, arg)
      isFirst = true
    }, delay)
  }
}

document.addEventListener('mousemove', debounce(function (e) {
  console.log('鼠标移动了', e)
}, 1000))
</script>

</body>
</html>

大型项目建议使用lodash的封装函数debounce/throttle

上一篇 下一篇

猜你喜欢

热点阅读