微信 头条小程序 记录一次电商项目倒计时活动优化
为了解决同一个页面需要开启多个定时器影响页面性能问题,封装了如下方法
封装一下函数 coundown.js
/**
* @function initSeckill 初始化函数,激活定时器调用
* @function clearCountdown 清除定时器
* 参数传入格式:[key:{},key:{}]
* key: {
* endTime startTime currentTime
* }
* key唯一标识,用于页面for循环渲染时能够准确找到对应的定时器key
*/
export function initSeckill(event) {
let obj = {};
for (let key in event) {
let t;
let endTime = event[key].endTime.split('.')[0].replace(new RegExp(/(-)/g), '/');
let startTime = event[key].startTime.split('.')[0].replace(new RegExp(/(-)/g), '/');
startTime = new Date(startTime).getTime();
endTime = new Date(endTime).getTime();
let currentTime = event[key].currentTime.replace(new RegExp(/(-)/g), '/');
currentTime = new Date(currentTime).getTime();
if(startTime > currentTime) {
t = (startTime - currentTime) / 1000;
}else {
t = (endTime - currentTime) / 1000;
}
obj[key] = t;
}
startCountDown(obj);
}
let times = null;
function startCountDown(t) {
let currentPages = getCurrentPages();
currentPages = currentPages[currentPages.length - 1];
times = setInterval(() => {
let resultsObj = {};
for (let key in t) {
if (t[key] > 0) {
t[key]--;
let {
day,
hour,
minute,
second
} = formatTime(t[key]);
if(day > 0) {
hour = (day * 24 + hour) >= 100 ? 99 : (day * 24 + hour)
}
hour = leadingZeros(hour);
minute = leadingZeros(minute);
second = leadingZeros(second);
resultsObj[key] = {hour,minute,second}
} else {
clearInterval(times);
times = null;
console.log('倒计时结束',key);
currentPages.countdownTimeout();
return;
}
}
currentPages.getNormalTime(resultsObj); //返回当前秒杀时间
}, 1000);
}
//处理时间格式
function formatTime(time) {
let seconds = time;
let day = Math.floor(seconds / (60 * 60 * 24));
let hour = Math.floor(seconds / (60 * 60)) - (day * 24);
let minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60);
let second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
return {
day,
hour,
minute,
second
};
}
//补零
function leadingZeros(num, length = 2) {
num = String(num)
if (num.length > length) return num
return (Array(length + 1).join(`0`) + num).substr(-length)
}
export function clearCountdown() {
clearInterval(times);
times = null;
}
使用
//引入coundown.js
import {
initSeckill,
clearCountdown
} from './countdown';
//在获取到列表数据时直接调用
/**
*seckillInfoObj [ key: {
* endTime startTime currentTime
* }]
*/
initSeckill(seckillInfoObj);
//在该清空定时器的地方
onHide() {
clearCountdown();
}