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

防抖

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

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

节流

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

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

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

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/

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值