/** * Set and convert the expiration time, return the time in seconds * * @param expire setting expire time parameters, support `number` or `string+format` (s/m/h/d) * @example * convertExpire('10s') // 10 seconds * convertExpire('10m') // 10 minutes * convertExpire('10h') // 10 hours * convertExpire('10d') // 10 days * convertExpire(30 * 1000) // 30 seconds * @return expires time in seconds */ export function convertExpire(expire: number | string): number { if (!expire) return 0; if (expire === -1) return -1; if (expire > 0) return expire as number; const matches = (expire as string).match(/^(\d+)([smhd])$/); if (!matches) return 0; const [, t, type] = matches as [any, number, string]; switch (type) { case 'm': return t * 60 * 1000; case 'h': return t * 60 * 60 * 1000; case 'd': return t * 24 * 60 * 60 * 1000; case 's': default: return t * 1000; } } export const formatTime = (date: Date) => { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour = date.getHours(); const minute = date.getMinutes(); const second = date.getSeconds(); return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second] .map(formatNumber) .join(':')}`; }; const formatNumber = (n: number) => { const s = n.toString(); return s[1] ? s : `0${s}`; }; /** * 获取当前页面中,选择器为 selector 的第一个node节点 * @param {String} selector 符合微信小程序规范的选择器 * @param {Object} context 调用环境,普通页面中为wx,自定义组件中为this;默认值为wx. * @return {Array} 返回一个数组,第一个元素为 node 节点 */ export const querySelector = function (selector: string, context = wx) { return new Promise((resolve, reject) => { context .createSelectorQuery() .select(selector) .boundingClientRect((res) => { if (res) { resolve(res); } else { reject(`不存在选择器为 ${selector} 的wxml`); } }) .exec(); }); }; /** * 限制函数的最大执行频率(两次执行间隔不能小于delay时间) * @param func 要执行的函数 * @param delay 延时时间,单位 ms * @param params 函数需要的参数 */ export function throttle(func: Function | ((context: any, params: any) => any), delay: number) { let timer: any; let lastTime = 0; return function (context: any, params: any) { if (timer) { clearTimeout(timer); } const now = Date.now(); const remainTime = delay - (now - lastTime); timer = setTimeout( () => { lastTime = now; func(context, params); }, remainTime > 0 ? remainTime : 0, ); }; }