util.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // 日期格式化1
  2. export function parseTime(time, pattern) {
  3. if (arguments.length === 0) {
  4. return null
  5. }
  6. const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  7. let date
  8. if (typeof time === 'object') {
  9. date = time
  10. } else {
  11. if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
  12. time = parseInt(time)
  13. }
  14. if ((typeof time === 'number') && (time.toString().length === 10)) {
  15. time = time * 1000
  16. }
  17. date = new Date(time)
  18. }
  19. const formatObj = {
  20. y: date.getFullYear(),
  21. m: date.getMonth() + 1,
  22. d: date.getDate(),
  23. h: date.getHours(),
  24. i: date.getMinutes(),
  25. s: date.getSeconds(),
  26. a: date.getDay()
  27. }
  28. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  29. let value = formatObj[key]
  30. // Note: getDay() returns 0 on Sunday
  31. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
  32. if (result.length > 0 && value < 10) {
  33. value = '0' + value
  34. }
  35. return value || 0
  36. })
  37. return time_str
  38. }
  39. /**
  40. * 防止小程序多次点击跳转
  41. * @param {*} obj
  42. * @returns
  43. */
  44. export function throttle(fn, gapTime) {
  45. if (gapTime == null || gapTime == undefined) {
  46. gapTime = 1500
  47. }
  48. let _lastTime = null
  49. uni.scanCode({
  50. success: function(res) {
  51. console.log('条码类型:' + res.scanType);
  52. console.log('条码内容:' + res.result);
  53. }
  54. });
  55. // 返回新的函数
  56. return function () {
  57. let _nowTime = + new Date()
  58. if (_nowTime - _lastTime > gapTime || !_lastTime) {
  59. fn.apply(this, arguments) //将this和参数传给原函数
  60. _lastTime = _nowTime
  61. }
  62. }
  63. }