🐴 记住了,节流(throttle)与防抖(debounce)

window.scroll 遇到sber,那是反复触发反复折磨。

不单单是scroll,还有resize,还有一系列鼠标事件mousemovemouseover、你来说几个moverenter

还有啥,鼠标的事件,还有那个啥键盘的事件。自己查一查看一看瞧一瞧过过脑。


有些人很急,有些人事很多,来回转轱辘。不是ta不好,是我不对,我还做得不够好不够牛,导致人家有钻子找我麻烦千百遍来回。

于是我被B出来了,出来个throttle

还出了个debounce

顺便说一下,input的input事件去查接口也要加上,免得来回请求接口轱辘轴转。


throttle

直接上代码吧。

js 复制代码
function throttle(fn, interval) {
  let last = 0
  
  return function () {
    let context = this
    let args = arguments
    let now = +new Date() // 加号将Date()对象转数字(时间戳),等于 new Date().getTime()
    
    if (now - last >= interval) {
      last = now;
      fn.apply(context, args)
    }
  }
}

咋个用法:

js 复制代码
const myScroll = throttle(() => console.log('来了老弟'), 1000)

document.addEventListener('scroll', myScroll)

就咋说呢,就是滚动到点了,再做事情,不到点你就瞎做呗,不理你。就这意思。不到点休想支使我休想使唤我。

debounce

js 复制代码
function debounce(fn, delay) {
  let timer = null
  
  return function () {
    let context = this
    let args = arguments
    
    if (timer) {
      clearTimeout(timer)
    }
    
    timer = setTimeout(function () {
      fn.apply(context, args)
    }, delay)
  }
}

咋用:

js 复制代码
const myScroll = debounce(() => console.log('来了老弟'), 1000)

document.addEventListener('scroll', myScroll)

还不好,比如说有个人,狂点,不等setTimeout做完事,这间隔中间又点了几个,等于又加了几个setTimeout,,这中间有多少个setTimeout计数器在等。

所以不好。

两者一结合,强强联合 throttle 和 debounce 强强结合

js 复制代码
function stronger(fn, delay) {
  let last = 0, timer = null
  
  return function () {
    let context = this
    let args = arguments
    let now = +new Date()
    
    if (now - last < delay) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now
        fn.apply(context, args)
      }, delay)
    } else {
      last = now
      fn.apply(context, args)
    }
  }
}

用吧,跟上面那样用。

用吧,不好用你🐴 我。

闭包

它俩就是闭包。

完事。

祝你成功,不成功也行,祝你有花不尽的钱花,不用抠抠搜搜的过一生。

相关推荐
冰暮流星9 分钟前
css新增盒子属性——尺寸调节
前端·css
程序员爱钓鱼10 分钟前
Python编程实战 - 函数与模块化编程 - 函数的定义与调用
前端·后端·python
欧阳码农11 分钟前
使用AI生成的页面总是被一眼认出来怎么办?1分钟给你解决
前端·后端
IT_陈寒17 分钟前
7个鲜为人知的JavaScript性能优化技巧,让你的应用提速50%!
前端·人工智能·后端
艾小码37 分钟前
前端别再乱存数据了!这3种存储方案让你的应用快如闪电
前端·javascript
黄毛火烧雪下38 分钟前
HTML 的底层原理
前端·html
Moment40 分钟前
面经分享——字节前端一面
前端·javascript·面试
十步杀一人_千里不留行3 小时前
Google 登录集成教程(Web + Expo 移动端)
前端
gAlAxy...6 小时前
IntelliJ IDEA 四种项目构建:从普通 Java 到 Maven Web 项目
前端·firefox
my一阁6 小时前
2025-web集群-问题总结
前端·arm开发·数据库·nginx·负载均衡·web