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

用吧,跟上面那样用。

用吧,不好用你🐴 我。

闭包

它俩就是闭包。

完事。

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

相关推荐
search721 小时前
前端设计:CRG 3--CDC error
前端
治金的blog21 小时前
vben-admin和vite,ant-design-vue的结合的联系
前端·vscode
利刃大大1 天前
【Vue】Vue2 和 Vue3 的区别
前端·javascript·vue.js
荔枝一杯酸牛奶1 天前
HTML 表单与表格布局实战:两个经典作业案例详解
前端·html
Charlie_lll1 天前
学习Three.js–纹理贴图(Texture)
前端·three.js
yuguo.im1 天前
我开源了一个 GrapesJS 插件
前端·javascript·开源·grapesjs
安且惜1 天前
带弹窗的页面--以表格形式展示
前端·javascript·vue.js
GISer_Jing1 天前
AI驱动营销:业务技术栈实战(From AIGC,待总结)
前端·人工智能·aigc·reactjs
GIS之路1 天前
GDAL 实现影像裁剪
前端·python·arcgis·信息可视化
AGMTI1 天前
webSock动态注册消息回调函数功能实现
开发语言·前端·javascript