util.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. export const formatTime = (date: Date) => {
  2. const year = date.getFullYear()
  3. const month = date.getMonth() + 1
  4. const day = date.getDate()
  5. const hour = date.getHours()
  6. const minute = date.getMinutes()
  7. const second = date.getSeconds()
  8. return (
  9. [year, month, day].map(formatNumber).join('/') +
  10. ' ' +
  11. [hour, minute, second].map(formatNumber).join(':')
  12. )
  13. }
  14. const formatNumber = (n: number) => {
  15. const s = n.toString()
  16. return s[1] ? s : '0' + s
  17. }
  18. /**
  19. * 函数防抖: 当事件被触发 n 秒后再执行回调,如果在 n 秒内又被触发,则重新计时。
  20. * @param {*} func
  21. * @param {*} wait
  22. * @returns { Function }
  23. */
  24. export const debounce = (func: any, wait: number) => {
  25. let delay = wait || 500;
  26. let timer: number | null;
  27. return () => {
  28. const _this = this;
  29. let args: any = arguments;
  30. if(timer) clearTimeout(timer);
  31. timer = setTimeout(() => {
  32. timer = null;
  33. func.apply(_this, args)
  34. }, delay)
  35. }
  36. }
  37. /**
  38. * 函数节流: 规定在一个单位时间内只能触发一次函数,如果在单位时间内触发多次,只执行一次。
  39. * @param {*} func
  40. * @param {*} wait
  41. * @returns { Function }
  42. */
  43. export const throttle = (func: { apply: (arg0: undefined, arg1: any) => void }, wait: number) => {
  44. let delay = wait || 500;
  45. let timer: number | null;
  46. return () => {
  47. let _this = this;
  48. let args = arguments;
  49. if(!timer) {
  50. timer = setTimeout(() => {
  51. func.apply(_this, args);
  52. timer = null;
  53. }, delay)
  54. }
  55. }
  56. }