手写节流函数

简介: JS查漏补缺系列是我在学习JS高级语法时做的笔记,通过实践费曼学习法进一步加深自己对其的理解,也希望别人能通过我的笔记能学习到相关的知识点。这一次我们来试着手写节流函数

节流的基本实现逻辑
image.png

基本实现


console.log(`发送了第${++counter}次网络请求`)

}

// 节流处理
inputEl.oninput = throttle(inputChange, 2000)

function throttle(fn, interval, options) {
// 1.记录上一次的开始时间
let lastTime = 0

// 2.事件触发时, 真正执行的函数
const _throttle = function() {

// 2.1.获取当前事件触发时的时间
const nowTime = new Date().getTime()

// 2.2.使用当前触发的时间和之前的时间间隔以及上一次开始的时间, 计算出还剩余多长时间需要去触发函数
const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
  // 2.3.真正触发函数
  fn()
  // 2.4.保留上次触发的时间
  lastTime = nowTime
}

}

return _throttle
}

功能优化——leading实现
:::info
有时候我们不想第一次输入的时候就发送请求,这时候我们最好做一个可选项供用户选择第一次的时候是否发送请求(leading: true/false)
:::

function throttle(fn, interval, options = { leading: true }) {
const { leading } = options
let lastTime = 0

const _throttle = function() {

const nowTime = new Date().getTime()
if (!lastTime && !leading) lastTime = nowTime

const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
  fn()
  lastTime = nowTime
}

}
return _throttle
}

功能优化——trailing 实现
:::info
用户在10s内输出了一些内容后停止输出,因为 “ 与上一次发送请求时的间隔不为10s“ 而没有发送请求
用户需求:想要在停止输出的10s后发送请求,即使最后一次输出没有达到与上一次发送请求的间隔为10s的要求
:::

function throttle(fn, interval, options = { leading: true, trailing: false }) {
const { leading, trailing } = options
let lastTime = 0
let timer = null


const _throttle = function() {

const nowTime = new Date().getTime()
if (!lastTime && !leading) lastTime = nowTime

const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
  // 在最后一次达到要求的情况下是不需要加上定时器的,要取消掉
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
  fn()
  lastTime = nowTime
  return  // return是为了防止被加上下面的定时器
}

if (trailing && !timer) {
  timer = setTimeout(() => {
    timer = null
    lastTime = !leading ? 0: new Date().getTime()
    fn()
  }, remainTime)
}

}

return _throttle
}

功能优化——this、参数改进
:::info
与防抖中this、参数改进使用的方法是一样的,用apply进行绑定this、arg,用剩余函数...arg接收参数
:::

function throttle(fn, interval, options = { leading: true, trailing: false }) {
const { leading, trailing } = options
let lastTime = 0
let timer = null
// 用剩余函数...arg接收参数
const _throttle = function(...args) {

const nowTime = new Date().getTime()
if (!lastTime && !leading) lastTime = nowTime

const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }

  //用apply进行绑定this、arg
  fn.apply(this, args)
  lastTime = nowTime
  return
}

if (trailing && !timer) {
  timer = setTimeout(() => {
    timer = null
    lastTime = !leading ? 0: new Date().getTime()
    fn.apply(this, args)
  }, remainTime)
}

}

return _throttle
}

功能优化——取消功能
:::info
场景:用户在输入东西之后防抖函数发送请求之前按到退出键退出了界面或按了取消按钮,这时我们就不用再发送请求
:::


// 在原来的外部script代码中添加取消功能的代码
_throttle.cancel = function() {

if(timer) clearTimeout(timer)
timer = null
lastTime = 0

}

功能优化——函数返回值
:::info
使用Promise来实现,resolve( ) 将结果进行回调出去
:::

function throttle(fn, interval, options = { leading: true, trailing: false }) {
const { leading, trailing, resultCallback } = options
let lastTime = 0
let timer = null

const _throttle = function(...args) {

return new Promise((resolve, reject) => {
  const nowTime = new Date().getTime()
  if (!lastTime && !leading) lastTime = nowTime

  const remainTime = interval - (nowTime - lastTime)
  if (remainTime <= 0) {
    if (timer) {
      clearTimeout(timer)
      timer = null
    }

    const result = fn.apply(this, args)
    if (resultCallback) resultCallback(result)
    resolve(result)
    lastTime = nowTime
    return
  }

  if (trailing && !timer) {
    timer = setTimeout(() => {
      timer = null
      lastTime = !leading ? 0: new Date().getTime()
      const result = fn.apply(this, args)
      if (resultCallback) resultCallback(result)
      resolve(result)
    }, remainTime)
  }
})

}

_throttle.cancel = function() {

if(timer) clearTimeout(timer)
timer = null
lastTime = 0

}

return _throttle
}

目录
相关文章
|
7天前
|
人工智能 运维 安全
|
5天前
|
人工智能 异构计算
敬请锁定《C位面对面》,洞察通用计算如何在AI时代持续赋能企业创新,助力业务发展!
敬请锁定《C位面对面》,洞察通用计算如何在AI时代持续赋能企业创新,助力业务发展!
|
6天前
|
机器学习/深度学习 人工智能 自然语言处理
B站开源IndexTTS2,用极致表现力颠覆听觉体验
在语音合成技术不断演进的背景下,早期版本的IndexTTS虽然在多场景应用中展现出良好的表现,但在情感表达的细腻度与时长控制的精准性方面仍存在提升空间。为了解决这些问题,并进一步推动零样本语音合成在实际场景中的落地能力,B站语音团队对模型架构与训练策略进行了深度优化,推出了全新一代语音合成模型——IndexTTS2 。
620 23
|
6天前
|
人工智能 测试技术 API
智能体(AI Agent)搭建全攻略:从概念到实践的终极指南
在人工智能浪潮中,智能体(AI Agent)正成为变革性技术。它们具备自主决策、环境感知、任务执行等能力,广泛应用于日常任务与商业流程。本文详解智能体概念、架构及七步搭建指南,助你打造专属智能体,迎接智能自动化新时代。
|
12天前
|
人工智能 JavaScript 测试技术
Qwen3-Coder入门教程|10分钟搞定安装配置
Qwen3-Coder 挑战赛简介:无论你是编程小白还是办公达人,都能通过本教程快速上手 Qwen-Code CLI,利用 AI 轻松实现代码编写、文档处理等任务。内容涵盖 API 配置、CLI 安装及多种实用案例,助你提升效率,体验智能编码的乐趣。
980 110
|
5天前
|
人工智能 数据可视化 数据挖掘
Quick BI 体验&征文有奖!
瓴羊生态推出Quick BI 征文激励计划,鼓励用户分享数据分析实践经验与技术洞察,征集高质量原创文章。内容围绕AI功能体验与BI案例实践,设季奖、年奖及参与奖,优秀作者可获现金奖励、产品内测资格及官方认证形象。投稿截止至2026年3月31日。
Quick BI 体验&征文有奖!