前端经典手写面试题---节流防抖

防抖

定义 : n 秒后在执行该事件,若在 n 秒内被重复触发,则重新计时。
场景:

  1. 搜索框搜索输入。只需用户最后一次输入完,再发送请求
  2. 手机号、邮箱验证输入检测
  3. 窗口大小resize。只需窗口调整完成后,计算窗口大小。防止重复渲染。
    实现
bash 复制代码
 const debounce = (fn,timeout)=>{
  let timer = null;
  return function(...arg){
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this,arg)
    }, timeout);
  }

节流

定义 : n 秒内只运行一次,若在 n 秒内重复触发,只有一次生效
场景:

  1. 滚动加载,加载更多或滚到底部监听
  2. 搜索框,搜索联想功能
    实现
bash 复制代码
  function throttle(fn,time) {
    let timer = null;
    return function(...arg) {
      if (timer) { return }
      timer = setTimeout(() => {
        fn.apply(this,arg) 
        timer = null
      }, time)
    }
  }

防抖节流函数中的this和参数问题

bash 复制代码
import React, { useState } from 'react';
import './App.css';

function App() {
  const obj = {a : 1};
  function throttle(fn,time) {
    let timer = null;
    
     //这里throttle返回的函数之所以用非箭头函数,是为了可以将它的this绑在一个对象上, 如下面的obj.final,就是把返回的函数绑在了obj上, 而fn用apply也会将this指向指定的执行环境
    return function(...arg) { //剩余参数语法会将函数内的所有剩余实参转换成一个数组,这里接受到的就是888
      console.log('this222',this) //this: obj
      if (timer) { return }
      
      timer = setTimeout(() => {
        console.log('this333',this) //这里的this是用的最近一个非箭头函数的this
        fn.apply(this,arg) // arg是一个数组,直接作为apply的参数即可
        timer = null
      }, time)
    }
  }
  
  function myFn(aaa){
    console.log(this, aaa) //this: obj ,aaa: 888
  }
 
  obj.final= throttle(myFn,1000)  //为了给这个myFn传参,得先在外面得到这个被节流的函数

  return (
    <div className="App" onClick={() => {obj.final('888')}}>
       <div className="wrap">
    </div>
    </div>
  );
}
export default App;

参考文章:

https://zhaocchen.github.io/docs/whiteboard/throttle-debounce/

相关推荐
如夏倾城38 分钟前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
图扑可视化1 小时前
基于图扑软件智慧制硅厂 Web SCADA 开发实践
前端·三维可视化·scada·hmi·组态软件
前端fighter2 小时前
2026年前端面试题总结(pdf版)
前端·pdf
谢小飞2 小时前
运维加了个参数,我们的网页挂掉了
前端·浏览器
CoderYanger3 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
用户69371750013846 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
徐小夕6 小时前
实测 10 个前端 UI 生成开源 Skill|AI 输出直达上线标准
前端·vue.js·github
tong_li6 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(八):AI 知道这字哪课学的(SQLite 结构化查询入门)
前端·langchain
用户69371750013846 小时前
当 Claude 开始反对蒸馏,我想起了那 700 万份盗版书籍
前端·后端·面试
zhanlang02176 小时前
HTML 零基础入门到企业实战全套教程【10.1】综合实战|从零开发静态企业官网:需求分析、页面结构规划、素材准备
前端·html