源码:
/**
-
Timer 类
/
export class Timer {
/*-
空的参数
-
@private
*/
constructor() {/**
- 把util函数的setTimeout次数赋值给this.settime
- @private
*/
this.settime = null;
}
/**
- Timer 初始化方法
- @param {Object} args - 前台Object参数.
*/
init(args) {
var that = this;
swan.request({
url: 'https://www.xxx.com', //请求时间接口,返回格式:{"result":"ok","time":"2019/11/7 10:04:14"}
method: 'GET',
dataType: 'json',
data: {
key: new Date().getTime()
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
if (res.data.result === "ok") {
if (typeof (args) == "object") {
that.render(args, res.data.time);
} else {
console.log("使用格式错误!");
}
}
},
fail: function (err) {
console.log('错误码:' + err.errCode);
console.log('错误信息:' + err.errMsg);
}
});
}
/**
- Timer 内部功能方法
- @param {Object} args - 前台Object参数.
- @param {String} time - 从后台接口获取到的当前服务器时间.
- @private
*/
render(args, time) {
var that = this,
endtime = args.endtime,
nowtime, diff;
nowtime = new Date(time).getTime(),
diff = (new Date().getTime() - nowtime);
that.util(endtime, nowtime, diff, args);
}
/**
- Timer 内部功能方法
- @param {String} endtime - 结束时间.
- @param {Number} nowtime - 服务器当前时间.
- @param {Number} diff - 客户端和服务器端的时间差.
- @param {Object} args - 前台Object参数.
- @private
*/
util(endtime, nowtime, diff, args) {
var d, h, m, s, ms, flag,
self = this,
timeGetTime = new Date(endtime).getTime(), //到期时间 毫秒数
nows = new Date().getTime(),
lefttime = parseInt((timeGetTime - nows + diff) / 1000);
d = parseInt(lefttime / 3600 / 24);
h = parseInt((lefttime / 3600) % 24);
m = parseInt((lefttime / 60) % 60);
s = parseInt(lefttime % 60);
ms = new Date().getMilliseconds();
s < 0 || s == 0 && m < 0 ? flag = true : flag = false;
self.settime = setTimeout(arguments.callee.bind(self, endtime, nowtime, diff, args), 50);
if (flag == true) {
clearTimeout(self.settime);
args.over.call(self, self.formatDate(nowtime));
} else {
args.show.call(self, d, h, m, s, ms, self.formatDate(nowtime));
}
}
/**
- Timer 内部格式化日期函数
- @param {number} now - 服务器时间戳.
- @private
*/
formatDate(now) {
var year = new Date(now).getFullYear(),
month = new Date(now).getMonth() + 1,
date = new Date(now).getDate(),
hour = new Date(now).getHours(),
minute = new Date(now).getMinutes(),
second = new Date(now).getSeconds();
return year + "/" + month + "/" + date + " " + hour + ":" + minute + ":" + second;
}
-
}
/* 小程序使用方法 */
// import { Timer } from '../../../lib/js/Timer.js'; //引入Timer类
// //倒计时时间
// var timer = new Timer();
// timer.init({
// "endtime": "2020/09/26 14:05:00",
// "show": function (d, h, m, s, ms, nowtime) {//时间没到前显示的内容
// console.log(d, h, m, s, ms, nowtime);
// },
// "over": function (nowtime) {//时间到了以后显示的内容
// console.log("过期",nowtime);
// }
// });
网友评论