utils.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // 防抖
  2. export const antiShake = (fn, t) => {
  3. let delay = t || 500;
  4. let timer;
  5. return function () {
  6. let args = arguments;
  7. if (timer) {
  8. clearTimeout(timer);
  9. }
  10. let callNow = !timer;
  11. timer = setTimeout(() => {
  12. timer = null;
  13. }, delay);
  14. if (callNow) fn.apply(this, args);
  15. };
  16. };
  17. // 点击防抖
  18. export const throttle = {
  19. bind: (el, binding) => {
  20. let throttleTime = binding.value; // 防抖时间
  21. if (!throttleTime) {
  22. // 用户若不设置防抖时间,则默认1s
  23. throttleTime = 1000;
  24. }
  25. let timer;
  26. let disable = false;
  27. el.addEventListener(
  28. "click",
  29. (event) => {
  30. if (timer) {
  31. clearTimeout(timer);
  32. }
  33. if (!disable) {
  34. // 第一次执行(一点击触发当前事件)
  35. disable = true;
  36. } else {
  37. event && event.stopImmediatePropagation();
  38. }
  39. timer = setTimeout(() => {
  40. timer = null;
  41. disable = false;
  42. }, throttleTime);
  43. },
  44. true
  45. );
  46. },
  47. };