Vue 中加入防抖函数与节流函数的使用

85 阅读1分钟

就是记录一下二个小函数, 通常会用到输入框要实时监听并保存时, 可以限制一下频率. 或者页面放大缩小时调用等. 实际情况看使用那个了.

先上代码, 我直接放在 helper.ts 文件里了

防抖函数

在一定时间内, 重量大量的输入, 只会算一次.

export function debounce(func: any, wait: number) {
  let timeout: any;
  return function (this: any) {
    const context = this;
    const args = arguments;
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
  };
}

const debounceFunc = debounce(() => {
  console.log('debounceFunc');
  // 调用 API 等
}, 1000)

// 这个可以在 input 等的 change 调用
const change = ()=> {
    debounceFunc()
}

节流函数

在一定时间内, 重量大量的输入, 按设定的时间, 均衡的输出.

export function throttle(func: any, limit: number) {
  let inThrottle: boolean;
  return function (this: any) {
    const args = arguments;
    const context: any = this;
    if (!inThrottle) {
      func.apply(context, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

const throttleFunc = throttle(() => {
  console.log('debounceFunc');
  // 计算一些东西等
}, 1000)

onMounted(() => {
  window.onresize = () => {
    throttleFunc()
  }
})