其他分享
首页 > 其他分享> > 性能优化

性能优化

作者:互联网

防抖

防抖(debounce)

所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间

<style>
  .box {
    width: 500px;
    height: 500px;
    background-color: #ccc;
    color: #fff;
    text-align: center;
    font-size: 100px;
  }
</style>
<div class="box"></div>
<script src="./lodash.min.js"></script>
const box = document.querySelector('.box')

let count = 0
function mouseMove () {
  box.innerHTML = ++count
}

function debounce (fn, t = 500) {
  let timer
  return function () {
    if(timer) clearTimeout(timer)

    timer = setTimeout(fn, t)
  }
}
//自定义
// box.addEventListener('mousemove', debounce(mouseMove, 500))
//Lodash库
box.addEventListener('mousemove', _.debounce(mouseMove, 500))

节流

节流(throttle)

所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数

使用场景 :轮播图点击效果 、 鼠标移动、页面尺寸缩放resize、滚动条滚动 就可以加节流

<script>
  const box = document.querySelector('.box')
  let i = 0

  function mouseMove () {
    box.innerHTML = ++i
  }

  // 节流函数
  // 控制box上文本多长时间修改一次
  function throttle (fn, t = 500) {

    // 开始时间
    let startTime = 0

    return function () {

      // 当前时间
      let now = Date.now()
      console.log(now)

      // 每隔500ms执行一次函数fn
      if(now - startTime >= t){
        // 调用函数
        fn()
        // startTime设置成当前时间
        startTime = now
      }
    }
  }

  // 监听事件
  //自定义
  //box.addEventListener('mousemove', throttle(mouseMove, 500))
 //lodash库
box.addEventListener('mousemove', _.throttle(mouseMove, 500))
</script>

标签:box,function,性能,mouseMove,let,now,优化,500
来源: https://www.cnblogs.com/yyshow/p/16314636.html