ascor
Version:
一些常用的简单的js工具
72 lines (71 loc) • 2.6 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { isFunction, isNumber } from "../is/index";
import { delay } from "./delay";
/**
* 倒计时,new Countdown(10,1) 10秒倒计时,以1秒的间隔倒数
*/
export class Countdown {
/**
* 倒计时
* @param {Number} s 单位秒,需要计时的总秒数
* @param {Number} step 倒计时间隔 (秒)
*/
constructor(s, step = 1) {
if (!isNumber(s)) {
throw new Error("倒计时时间必须为数值");
}
if (!isNumber(step)) {
throw new Error("时间间隔必须为数值");
}
this.countBak = this.count = s;
this.stepBak = this.step = step;
}
/**
* 开始倒计时
* @param {Function} fn 回调函数
*/
run(fn) {
return __awaiter(this, void 0, void 0, function* () {
try {
if (isFunction(fn)) {
if ((yield fn(this.count)) !== false) {
yield delay(this.step * 1000);
if (this.count > 0) {
this.count -= this.step;
this.run(fn);
}
else {
this.reset();
}
}
}
}
catch (error) {
console.error(error);
}
});
}
/**
* 重置秒数
* @param {Number} s 秒数,可选 ,不传默认为创建实例时的时间
* @param {Number} step 时间间隔(秒),可选 ,不传默认为创建实例时的时间间隔
*/
reset(s = this.countBak, step = this.stepBak) {
if (!isNumber(s)) {
s = this.countBak;
}
if (!isNumber(step)) {
step = this.stepBak;
}
this.countBak = this.count = s;
this.stepBak = this.step = step;
}
}