🐴 记住了,节流(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)
    }
  }
}

用吧,跟上面那样用。

用吧,不好用你🐴 我。

闭包

它俩就是闭包。

完事。

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

相关推荐
GIS之路8 小时前
ArcGIS Pro 中的 Notebooks 入门
前端
IT_陈寒10 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
Kagol11 小时前
TinyVue 支持 Skills 啦!现在你可以让 AI 使用 TinyVue 组件搭建项目
前端·agent·ai编程
柳杉11 小时前
从零打造 AI 全球趋势监测大屏
前端·javascript·aigc
simple_lau11 小时前
Cursor配置MasterGo MCP:一键读取设计稿生成高还原度前端代码
前端·javascript·vue.js
睡不着先生11 小时前
如何设计一个真正可扩展的表单生成器?
前端·javascript·vue.js
天蓝色的鱼鱼11 小时前
模块化与组件化:90%的前端开发者都没搞懂的本质区别
前端·架构·代码规范
明君8799711 小时前
Flutter 如何给图片添加多行文字水印
前端·flutter
leolee1811 小时前
Redux Toolkit 实战使用指南
前端·react.js·redux
bluceli11 小时前
React Hooks最佳实践:写出优雅高效的组件代码
前端·react.js