防抖节流

防抖节流(重点)

浏览器的极限绘制频率60侦,计时器的话大概为16.666

高频触发的业务:抽奖 登录 动画 网络加载等等需要

// 登录 防抖
function fangdou(cb,delay) {
  var timer = null
  reture function() {
    let arg = arguments
    clearTimeout(timer)
    timer = setTimeout(()=>{cb()},delay)
  }
}
document.onclick = fangdou(function(e) {
  // 操作
},1000)
// 滑动 节流 每隔一段时间调用一次
function move(cb,delay) {
  var timer = null
  return function() {
    let arg = arguments
    if(!timer) {
      timer = setTimeout(()=>{
        cb.apply(this,arg)
      },delay)
      timer = null
    }
  }
}
document.onmousemove = move(function() {
  // 操作
},1000)

优化this 通过时间戳和计时器来设计

posted @ 2022-08-29 10:31  a立方  阅读(20)  评论(0)    收藏  举报