Skip to content
Snippets Groups Projects
Commit 2531708d authored by Ayc0's avatar Ayc0
Browse files

feat: change interval to add .trigger() method

parent 2f0279aa
No related branches found
No related tags found
No related merge requests found
......@@ -2,10 +2,31 @@
const jwt = require('jsonwebtoken');
const { cert } = require('./config');
const interval = (fn, initialTTL, output = { id: null, clear: () => undefined }) => {
const timeoutID = setTimeout(async () => {
const initialOutput = { id: null, clear: () => undefined, trigger: () => undefined };
const replace = (toReplace, replacer) => {
Object.keys(replacer).forEach((x) => {
toReplace[x] = replacer[x];
});
};
function Timeout(fn, interval) {
this.id = setTimeout(fn, interval);
this.cleared = false;
this.clear = () => {
this.cleared = true;
clearTimeout(this.id);
};
}
const interval = (fn, initialTTL, output = initialOutput) => {
const getTimeout = ttl =>
new Timeout(async () => {
let TTL;
try {
if (this.cleared) {
return;
}
TTL = fn();
if (TTL instanceof Promise) {
TTL = await TTL;
......@@ -14,11 +35,24 @@ const interval = (fn, initialTTL, output = { id: null, clear: () => undefined })
console.error(error);
TTL = initialTTL;
}
if (this.cleared) {
return;
}
const nextTTL = parseInt(TTL, 10) || initialTTL;
interval(fn, nextTTL, output);
}, initialTTL);
output.id = timeoutID;
output.clear = () => clearTimeout(timeoutID);
}, ttl);
const getOutput = timeout => ({
id: timeout.id,
clear: () => timeout.clear(),
trigger: () => {
timeout.clear();
const newTimeout = getTimeout(0);
replace(output, getOutput(newTimeout));
},
});
const timeout = getTimeout(initialTTL);
replace(output, getOutput(timeout));
return output;
};
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment