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

用吧,跟上面那样用。

用吧,不好用你🐴 我。

闭包

它俩就是闭包。

完事。

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

相关推荐
IT_陈寒33 分钟前
Python 3.12新特性实战:5个让你的代码提速30%的性能优化技巧
前端·人工智能·后端
sniper_fandc1 小时前
Vue Router路由
前端·javascript·vue.js
excel1 小时前
为什么 Vue 组件中的 data 必须是一个函数?(含 Vue2/3 对比)
前端
妄小闲1 小时前
成品网站模板源码 网站源码模板 html源码下载
前端·html
知识分享小能手9 小时前
微信小程序入门学习教程,从入门到精通,微信小程序常用API(上)——知识点详解 + 案例实战(4)
前端·javascript·学习·微信小程序·小程序·html5·微信开放平台
清灵xmf10 小时前
CSS field-sizing 让表单「活」起来
前端·css·field-sizing
文火冰糖的硅基工坊10 小时前
[光学原理与应用-480]:《国产检测设备对比表》
前端·人工智能·系统架构·制造·半导体·产业链
excel10 小时前
Qiankun 子应用生命周期及使用场景解析
前端
weixin_4462608510 小时前
Django - 让开发变得简单高效的Web框架
前端·数据库·django
ObjectX前端实验室11 小时前
【react18原理探究实践】异步可中断 & 时间分片
前端·react.js