funcManager.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * 函数相关类
  3. */
  4. export class FuncManager {
  5. constructor() {
  6. // 防抖定时器
  7. this.timeout = null;
  8. // 节流定时器
  9. this.timer = null;
  10. this.flag = null;
  11. }
  12. /**
  13. * @description 进行延时,以达到可以简写代码的目的 比如: await sleep(20)将会阻塞20ms
  14. * @param {number} value 堵塞时间 单位ms 毫秒
  15. * @returns {Promise} 返回promise
  16. */
  17. sleep = (value = 30) => {
  18. return new Promise((resolve) => {
  19. setTimeout(() => {
  20. resolve()
  21. }, value)
  22. })
  23. }
  24. /**
  25. * 是否是函数
  26. */
  27. isFunc = (value) => {
  28. return typeof value === 'function'
  29. }
  30. /**
  31. * 防抖原理:一定时间内,只有最后一次操作,再过wait毫秒后才执行函数
  32. *
  33. * @param {Function} func 要执行的回调函数
  34. * @param {Number} wait 延时的时间
  35. * @param {Boolean} immediate 是否立即执行
  36. * @return null
  37. */
  38. debounce = (func, wait = 500, immediate = false) => {
  39. // 清除定时器
  40. if (this.timeout !== null) clearTimeout(this.timeout)
  41. // 立即执行,此类情况一般用不到
  42. if (immediate) {
  43. const callNow = !this.timeout
  44. this.timeout = setTimeout(() => {
  45. this.timeout = null
  46. }, wait)
  47. if (callNow) typeof func === 'function' && func()
  48. } else {
  49. // 设置定时器,当最后一次操作后,timeout不会再被清除,所以在延时wait毫秒后执行func回调方法
  50. this.timeout = setTimeout(() => {
  51. typeof func === 'function' && func()
  52. }, wait)
  53. }
  54. }
  55. /**
  56. * 节流原理:在一定时间内,只能触发一次
  57. *
  58. * @param {Function} func 要执行的回调函数
  59. * @param {Number} wait 延时的时间
  60. * @param {Boolean} immediate 是否立即执行
  61. * @return null
  62. */
  63. throttle = (func, wait = 500, immediate = true) => {
  64. if (immediate) {
  65. if (!this.flag) {
  66. this.flag = true
  67. // 如果是立即执行,则在wait毫秒内开始时执行
  68. typeof func === 'function' && func()
  69. this.timer = setTimeout(() => {
  70. this.flag = false
  71. }, wait)
  72. }
  73. } else if (!this.flag) {
  74. this.flag = true
  75. // 如果是非立即执行,则在wait毫秒内的结束处执行
  76. this.timer = setTimeout(() => {
  77. this.flag = false
  78. typeof func === 'function' && func()
  79. }, wait)
  80. }
  81. }
  82. /**
  83. * 显示消息提示框
  84. * @param {String} title 提示的内容,长度与 icon 取值有关。
  85. * @param {Function} func 执行完后的执行函数
  86. * @param {Number} duration 提示的延迟时间,单位毫秒,默认:2000
  87. */
  88. toast = (title, func = null, duration = 2000) => {
  89. uni.showToast({
  90. title: String(title),
  91. icon: 'none',
  92. duration
  93. })
  94. if (typeof func === "function") {
  95. setTimeout(() => {
  96. func();
  97. }, duration)
  98. }
  99. }
  100. }