index.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. export function debounce(func, wait, immediate) {
  2. let timeout, args, context, timestamp, result;
  3. const later = function () {
  4. // 据上一次触发时间间隔
  5. const last = +new Date() - timestamp;
  6. // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
  7. if (last < wait && last > 0) {
  8. timeout = setTimeout(later, wait - last);
  9. } else {
  10. timeout = null;
  11. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  12. if (!immediate) {
  13. result = func.apply(context, args);
  14. if (!timeout) context = args = null;
  15. }
  16. }
  17. };
  18. return function (...args) {
  19. context = this;
  20. timestamp = +new Date();
  21. const callNow = immediate && !timeout;
  22. // 如果延时不存在,重新设定延时
  23. if (!timeout) timeout = setTimeout(later, wait);
  24. if (callNow) {
  25. result = func.apply(context, args);
  26. context = args = null;
  27. }
  28. return result;
  29. };
  30. }
  31. // 定义一个函数来填充数组
  32. export function fillArray(array, targetLength, fillValue) {
  33. while (array.length < targetLength) {
  34. array.push(fillValue);
  35. }
  36. }