common.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * @desc 函数防抖
  3. * @param func 目标函数
  4. * @param wait 延迟执行毫秒数
  5. * @param immediate true - 立即执行, false - 延迟执行
  6. */
  7. export const debounce = function(func, wait = 1000, immediate = true) {
  8. let timer;
  9. console.log(1);
  10. return function() {
  11. console.log(123);
  12. let context = this,
  13. args = arguments;
  14. if (timer) clearTimeout(timer);
  15. if (immediate) {
  16. let callNow = !timer;
  17. timer = setTimeout(() => {
  18. timer = null;
  19. }, wait);
  20. if (callNow) func.apply(context, args);
  21. } else {
  22. timer = setTimeout(() => {
  23. func.apply(context, args);
  24. }, wait)
  25. }
  26. }
  27. }
  28. /**
  29. * @desc 函数节流
  30. * @param func 函数
  31. * @param wait 延迟执行毫秒数
  32. * @param type 1 使用表时间戳,在时间段开始的时候触发 2 使用表定时器,在时间段结束的时候触发
  33. */
  34. export const throttle = (func, wait = 1000, type = 1) => {
  35. let previous = 0;
  36. let timeout;
  37. return function() {
  38. let context = this;
  39. let args = arguments;
  40. if (type === 1) {
  41. let now = Date.now();
  42. if (now - previous > wait) {
  43. func.apply(context, args);
  44. previous = now;
  45. }
  46. } else if (type === 2) {
  47. if (!timeout) {
  48. timeout = setTimeout(() => {
  49. timeout = null;
  50. func.apply(context, args)
  51. }, wait)
  52. }
  53. }
  54. }
  55. }