微信小程序 - - - - -封装部分公用方法

1. 方法封装

let moment = require('dayjs')

/**
 * 格式换时间
 * @param {*} value 时间
 * @param {*} type 格式
 */
const formatTime = (value = new Date(), type = "YYYY-MM-DD HH:mm:ss") => {
  return moment(value).format(type);
};

/**
 * 目标时间是否在当前之间之后
 * @param {*} targetTime 
 * @param {*} sourceTime 
 */
const chronologicalOrder = (targetTime = '2022-08-25 19:36:16', sourceTime = new Date()) => {
  return moment(targetTime).isAfter(moment(sourceTime))
}


/**
 *
 * @param {*} cb 回调函数
 * @param {*} delay 延时时间
 */
const debounce = (cb, delay = 1000) => {
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      cb.apply(this, arguments);
    }, delay);
  };
};

/**
 * 
 * @param {*} cb 回调函数
 * @param {*} delay 延时时间
 */
const throttle = (cb, delay = 1000) => {
  //距离上一次的执行时间
  let lastTime = 0;
  return function () {
    let _this = this;
    let _arguments = arguments;
    let now = new Date().getTime();
    //如果距离上一次执行超过了delay才能再次执行
    if (now - lastTime > delay) {
      cb.apply(_this, _arguments);
      lastTime = now;
    }
  };
};

export {
  formatTime,
  chronologicalOrder,
  debounce,
  throttle
};

2. app.js 引入挂载

// app.js
let {
  formatTime,
  chronologicalOrder,
  debounce,
  throttle
} = require('./utils/index.js')

App({
  onLaunch() {},
  formatTime,
  chronologicalOrder,
  debounce,
  throttle
})

3. 具体使用

// index.js
const app = getApp()


Page({
	// throttle 的使用
	lower: app.throttle(function () {
		// to do something ...
	}, 1000),


	// formatTime 的使用
	formatTimeFunc(){
		 app.formatTime(new Date()); // 格式化当前时间 使用默认格式
		 app.formatTime(new Date(), 'YYYY年MM月DD日');// 格式化当前时间 使用指定格式 'YYYY年MM月DD日'
	},

	// chronologicalOrder 的使用
	isAfterThe specifiedDate(){
		app.chronologicalOrder('2039.12.24'); // 2039.12.24 是不是在当前日期之后
		app.chronologicalOrder('2039.12.24', '2022.9.29'); // 2039.12.24 是不是在2022.9.29之后
	},

})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值