common.js 1.2 KB

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