#说明

将收录防抖与节流操作相关工具

笔记分享:hongjilin

一、防抖

Ⅰ-通用防抖

  1. 工具代码写法示例1
  1. //Tool.ts
  2. // 防抖1
  3. deBounce = (
  4. fn: (...args: any[]) => any,
  5. interval: number
  6. ): ((...args: any[]) => any) => {
  7. let timer = null;
  8. return (e) => {
  9. if (timer) {
  10. clearTimeout(timer);
  11. timer = null;
  12. }
  13. timer = setTimeout(() => {
  14. fn(e);
  15. }, interval);
  16. };
  17. };
  1. 写法示例2
  1. /**
  2. * 防抖1
  3. * @param fnc 传入函数
  4. * @param params
  5. * @param t
  6. * @returns
  7. */
  8. DebounceSendSMSCode = (fnc, params, t) => {
  9. let delay = t || 200; // 默认0.2s
  10. let timer;
  11. return function () {
  12. if (timer) {
  13. clearTimeout(timer);
  14. }
  15. timer = setTimeout(() => {
  16. timer = null;
  17. fnc(...params)
  18. }, delay);
  19. }
  20. }
  1. 对于写法2的调用
  1. import { tool } from '~/utils/Tool'
  2. //准备添加防抖的函数
  3. const sendSMSCode = async (phoneItem, index) => {....}
  4. // 防抖,传入函数,参数,以及秒数
  5. onClick={tool.DebounceSendSMSCode(sendSMSCode, [phoneItem, index], 300)}

Ⅱ-Echart防抖自适应

此函数适用于echart

  1. 当我需要让Echart的折线图根据当前页面大小发生变化,并且进行防抖处理节约性能

  2. 分析:

    1. 利用柯里化高阶函数的知识点写防抖函数
    2. 利用Echartresize()刷新函数进行适配
  3. 代码示例

防抖函数代码

  1. /**
  2. * 防抖进行echart自适应
  3. * @param chartDom 传入 echarts.init(chartDom);生成的对象
  4. */
  5. debounceEchartResize = () => {
  6. let timers
  7. return (chartDom,interval:number) => {
  8. if (timers) clearTimeout(timers);
  9. timers = setTimeout(() => { // 只执行最后一个定时器的 结果
  10. chartDom.resize()
  11. }, interval); // 推迟 300 ms 在执行resize 效果
  12. // return timer
  13. }
  14. }

js调用—>本代码在React hooks 中使用

```tsx import { tool } from ‘~/utils/Tool’ const SaleSumInfo = (props: IProps) => { //柯里化调用防抖自适应,在此处第一次调用,会生成timer,这样就不会因为在副作用函数中 //因为重复渲染而重置 const debounceResize = tool.debounceEchartResize()

//副作用函数,作用是react的生命周期 useEffect(() => { const chartDom = document.getElementById(‘main’); const myChart = echarts.init(chartDom); //形成闭包,同时防止监听事件运行两次回调函数 const resizeFunc=()=>debounceResize(myChart,300) //创建监听事件 window.addEventListener(“resize”,resizeFunc) //销毁的生命周期 进行监听卸载 return ()=>{ window.removeEventListener(“resize”,resizeFunc) }

  1. //渲染函数
  2. return ()

} }

  1. > 4. 效果示例图
  2. > ![](JavaScirpt%E5%B7%A5%E5%85%B7%E5%B0%81%E8%A3%85%E4%B8%AD%E7%9A%84%E5%9B%BE%E7%89%87/Echart%E8%87%AA%E9%80%82%E5%BA%94%E9%98%B2%E6%8A%96%E5%87%BD%E6%95%B0%E7%A4%BA%E4%BE%8B.gif#alt=)
  3. <a name="2b0c4f54"></a>
  4. # 二、节流
  5. <a name="59640f64"></a>
  6. ## Ⅰ-通用节流
  7. > 代码示例
  8. > ```tsx
  9. // 节流
  10. throttle = (fn: Function, interval: number) => {
  11. let canRun = true;
  12. return () => {
  13. if (!canRun) {
  14. return;
  15. }
  16. canRun = false;
  17. setTimeout(() => {
  18. fn();
  19. canRun = true;
  20. }, interval);
  21. };
  22. };