Skip to content

JS 防抖实现

约 364 字大约 1 分钟

JavaScript

2020-12-31

在 JavaScript 中,**防抖(debounce)**可以防止按钮被短时间内连续点击多次。你可以使用 setTimeout 来延迟执行按钮点击的回调函数,并在每次点击时清除之前的定时器,确保只有最后一次点击后的回调会被执行。

方式 1:使用 setTimeout 实现防抖

function debounce(fn, delay) {
  let timer;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

// 按钮点击事件
const handleClick = debounce(() => {
  console.log("按钮被点击了");
}, 500);

document.getElementById("btn").addEventListener("click", handleClick);

解释

  • 每次点击按钮时,都会清除之前的定时器 clearTimeout(timer),然后重新启动 setTimeout
  • 只有在最后一次点击后 500ms 内没有新的点击 时,函数 fn 才会执行。

方式 2:使用 Lodash 的 debounce

如果你的项目中已经引入了 Lodash,可以直接使用其 _.debounce 方法:

// 先安装 lodash(如果还没安装)
// npm install lodash

import _ from "lodash";

const handleClick = _.debounce(() => {
  console.log("按钮被点击了");
}, 500);

document.getElementById("btn").addEventListener("click", handleClick);

Lodash 的 debounce 还支持更多功能,如立即执行模式 { leading: true, trailing: false }


方式 3:在 Vue 或 React 中使用

Vue 3:

<template>
  <button @click="handleClick">点击</button>
</template>

<script>
import { ref } from "vue";
import _ from "lodash";

export default {
  setup() {
    const handleClick = _.debounce(() => {
      console.log("Vue 按钮被点击");
    }, 500);

    return { handleClick };
  },
};
</script>

React:

import { useCallback } from "react";
import _ from "lodash";

const MyButton = () => {
  const handleClick = useCallback(
    _.debounce(() => {
      console.log("React 按钮被点击");
    }, 500),
    []
  );

  return <button onClick={handleClick}>点击</button>;
};