UNPKG

@js-plus/count-down

Version:
126 lines (120 loc) 3.88 kB
var CountDown = (function (exports) { 'use strict'; /** * 定义倒计时Countdown类 * * 可以用于各种倒计时场景 */ class Countdown { /** * 实例化一个倒时器 * @param timeLeft 剩余时间 * @param intervalHook * @param endHook */ constructor(timeLeft, intervalHook, endHook) { this.timers = []; this.timeLeft = 0; this.endHooks = []; this.intervalHooks = []; this.endTime = new Date(); this.startTime = new Date(); this.setTimeLeft(timeLeft || 0); this.setInterval = setInterval; this.clearInterval = clearInterval; // 设置钩子 endHook && this.addEndHook(endHook); // 设置钩子 intervalHook && this.addIntervalHook(intervalHook); // 如果设置了倒计时立刻执行 timeLeft && timeLeft > 0 && this.run(); } /** * 设置剩余时间 * * @param timeLeft 剩余时间 */ setTimeLeft(timeLeft) { this.startTime = new Date(); this.endTime = new Date(this.startTime.getTime() + timeLeft * 1000); } /** * 如果传入的是数组,将每一秒要执行的回调函数push进该数组 * * @param intervalHook 间隔回调钩子 */ addIntervalHook(intervalHook) { if (!Array.isArray(this.intervalHooks)) { this.intervalHooks = []; } this.intervalHooks.push(intervalHook); } /** * 生成倒计时结束数组,将倒计时结束的回调函数push进该数组 * */ addEndHook(endHook) { if (!Array.isArray(this.endHooks)) { this.endHooks = []; } this.endHooks.push(endHook); } /** * 强制检测剩余时间,同时触发 * * @param isEmitHook 是否触发间隔回调钩子 */ checkTime(isEmitHook) { // 判断是否结束 const isEnd = this.isEnd(); // 清除定时器 isEnd && this.clearTimeRun(); if (isEmitHook) { // 每秒回调 Array.isArray(this.intervalHooks) && this.intervalHooks.forEach(hook => typeof hook === 'function' && hook.call(this, this.timeLeft, isEnd, this)); // 结束回调 isEnd && Array.isArray(this.endHooks) && this.endHooks.forEach(hook => typeof hook === 'function' && hook.call(this, this)); } } /** * 判断是否结束 * @returns 是否结束 */ isEnd() { // 计算剩余时间 this.timeLeft = (this.endTime.getTime() - new Date().getTime()) / 1000; // 判断是否结束 return this.timeLeft <= 0; } clearTime() { // 清除定时器 this.clearTimeRun(); // 检测时间 this.checkTime(true); } clearTimeRun() { // 归零时间 this.endTime = new Date(); // 清理所有定时器 this.clearIntervals(); } clearIntervals() { // 清理定时器 Array.isArray(this.timers) && this.timers.forEach(timer => this.clearInterval(timer)); } run() { // 清理所有定时器 this.clearIntervals(); // 加入定时器 this.timers.push(this.setInterval(this.checkTime.bind(this), 1000)); } } exports.Countdown = Countdown; exports.default = Countdown; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}));