Add alarms api
This commit is contained in:
parent
ad0a7fe22a
commit
bb183f4211
1 changed files with 54 additions and 0 deletions
54
src/utils.ts
54
src/utils.ts
|
@ -16,3 +16,57 @@ export const rotateArray = <T>(arr: T[], reverse = false): T[] => {
|
||||||
else arr.push(arr.shift()!);
|
else arr.push(arr.shift()!);
|
||||||
return arr;
|
return arr;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type resolveCallback<T> = (value: T) => void;
|
||||||
|
type rejectCallback = (reason?: unknown) => void;
|
||||||
|
export const newPromise = <T>(): [
|
||||||
|
Promise<T>,
|
||||||
|
resolveCallback<T>,
|
||||||
|
rejectCallback
|
||||||
|
] => {
|
||||||
|
let resolve: resolveCallback<T>;
|
||||||
|
let reject: rejectCallback;
|
||||||
|
const promise = new Promise(
|
||||||
|
(res: resolveCallback<T>, rej: rejectCallback) => {
|
||||||
|
resolve = res;
|
||||||
|
reject = rej;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return [promise, resolve!, reject!];
|
||||||
|
};
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
alarmsMap?: Map<any, [Promise<void>, rejectCallback]>;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//Clone of the https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/alarms
|
||||||
|
export namespace Alarms {
|
||||||
|
const getMap = () => {
|
||||||
|
window.alarmsMap ??= new Map();
|
||||||
|
return window.alarmsMap;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const create = (delay: number, name?: any) => {
|
||||||
|
const map = getMap();
|
||||||
|
const alrm = map.get(name);
|
||||||
|
if (alrm) alrm[1]();
|
||||||
|
|
||||||
|
const [promise, resolve, reject] = newPromise<void>();
|
||||||
|
const timeout = setTimeout(resolve, delay);
|
||||||
|
promise.catch(() => window.clearTimeout(timeout));
|
||||||
|
|
||||||
|
if (name != undefined) map.set(name, [promise, reject]);
|
||||||
|
return promise;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const get = (name: any) => (getMap().get(name) ?? [])[0];
|
||||||
|
export const getAll = () => Array.from(getMap().entries()).map((a) => a[0]);
|
||||||
|
|
||||||
|
export const clear = (name: any) => {
|
||||||
|
const alrm = getMap().get(name);
|
||||||
|
if (alrm) alrm[1]();
|
||||||
|
};
|
||||||
|
export const clearAll = () => getMap().forEach((a) => a[1]());
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue