Skip to content

函数

防抖函数(debounce)

  • 高频
  • 耗时
  • 执行最后一次

示例代码

以下是一个简单的防抖函数实现:

javascript
import { ref, onMounted } from "vue";

const result = ref("");

// 需要处理的函数
const f = () => {
  result.value += "resize\n";
};

// 函数防抖
const debounce = (func, wait: number = 500) => {
  let timeout;

  return function (this: any, ...args: any[]) {
    const context = this;
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
};

// 经过防抖处理的函数
const fDebounce = debounce(f);

// 使用示例
onMounted(() => {
  window.addEventListener("resize", fDebounce);
});

示例

拖动浏览器,改变大小