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

防抖

定义 : 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/

相关推荐
小璞1 分钟前
01_CursorRules_需求理解篇_Rule_requirement-understanding
前端
老虎062713 分钟前
JavaWeb前端02(JavaScript)
开发语言·前端·javascript
耀耀切克闹灬14 分钟前
WEB前端基础知识梳理(四)
前端
anyup24 分钟前
🔥🔥 10 天 Star 破百!uView Pro 文档也开源啦:完全免费、无广告、高效上手
前端·vue.js·uni-app
puppy0_029 分钟前
Webpack 打包流程及 Hooks 汇总
前端·webpack·前端工程化
Rasir30 分钟前
第七章:高级特性与项目优化
前端
春日野柚30 分钟前
前端打包优化分析
前端·webpack
yvvvy34 分钟前
DNS 解析全解析:从域名到 IP 的“桥梁”之旅
前端
柯南二号39 分钟前
【后端】SpringBoot中HttpServletRequest参数为啥不需要前端透传
前端·spring boot·后端
Dignity_呱1 小时前
如何在不发版时,实现小程序的 AB 测试?
前端·面试·微信小程序