@550w-tools/core
Version:
550w-tools 核心库,暴露若干API供应用层调用
38 lines • 1.13 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.QPSTimer = exports.getEachMinTimeByQPS = void 0;
// 根据QPS计算出一次任务至少需要执行多久
function getEachMinTimeByQPS(qps = 1) {
return (1 / qps) * 1000;
}
exports.getEachMinTimeByQPS = getEachMinTimeByQPS;
/**
* @description QPS限制任务时间管理器
*/
class QPSTimer {
static getEachMinTimeByQPS(qps = 1) {
return (1 / qps) * 1000;
}
constructor(qps) {
this.qps = qps;
this.eachMinTime = getEachMinTimeByQPS(qps);
}
// 任务开始前调用开始计时
start() {
this.startTime = Date.now();
// 简化使用
return this;
}
// 等待QPS限制下的剩余时长
async wait() {
const takesTime = Date.now() - this.startTime;
// 任务执行完成后剩余等待时长
const waitTime = this.eachMinTime - takesTime;
if (waitTime > 0) {
await new Promise((r) => setTimeout(r, waitTime));
}
return waitTime;
}
}
exports.QPSTimer = QPSTimer;
//# sourceMappingURL=qps.js.map