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

防抖

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

相关推荐
青衫码上行几秒前
【JavaWeb学习 | 第二篇】CSS(1) - 基础语法与核心概念
前端·css·学习
残冬醉离殇16 分钟前
🔥 什么?不用鼠标点击也能触发点击事件???前端工程师的认知塌了!
前端·javascript
重铸码农荣光23 分钟前
从 DOM 渲染到代码优雅:ES6 字符串模板与 map 的实战指南
前端·html
前端小咸鱼一条23 分钟前
14. setState是异步更新
开发语言·前端·javascript
jump68038 分钟前
Cookie SessionStorage Localstorage的区别
前端
gustt40 分钟前
JavaScript 字符串深度解析:模板字符串与常用方法详解
前端·javascript·代码规范
UIUV40 分钟前
JavaScript 入门笔记:从基础语法到现代特性
前端·javascript
Qinana1 小时前
💖用 CSS 打造会“亲吻”的动画小球
前端·css
Mintopia1 小时前
⚙️ 用 Next.js 玩转压测:**200 Requests/s 的华丽舞步**
前端·javascript·全栈