合同小程序前端代码仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
1017 B

  1. // @ts-nocheck
  2. /**
  3. *
  4. * @param fn
  5. * @param wait
  6. * @returns
  7. */
  8. export function debounce<A extends any>(fn : (args: A)=> void, wait = 300): (args: A)=> void {
  9. let timer = -1
  10. return (args: A) => {
  11. if (timer >-1) {clearTimeout(timer)};
  12. timer = setTimeout(()=>{
  13. fn(args)
  14. }, wait)
  15. }
  16. };
  17. // 示例
  18. // 定义一个函数
  19. // function saveData(data: string) {
  20. // // 模拟保存数据的操作
  21. // console.log(`Saving data: ${data}`);
  22. // }
  23. // // 创建一个防抖函数,延迟 500 毫秒后调用 saveData 函数
  24. // const debouncedSaveData = debounce(saveData, 500);
  25. // // 连续调用防抖函数
  26. // debouncedSaveData('Data 1'); // 不会立即调用 saveData 函数
  27. // debouncedSaveData('Data 2'); // 不会立即调用 saveData 函数
  28. // 在 500 毫秒后,只会调用一次 saveData 函数,输出结果为 "Saving data: Data 2"