forked from clerk/javascript
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworkerTimers.worker.ts
40 lines (36 loc) · 1.24 KB
/
workerTimers.worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import type { WorkerTimerEvent, WorkerTimerId, WorkerTimerResponseEvent } from './workerTimers.types';
// This file is loaded as TEXT by esbuild during build
// and fed into a blob so we can easily instantiate the web worker
// look at the tsup.config.ts file for more details on the loader
const respond = (p: WorkerTimerResponseEvent) => {
self.postMessage(p);
};
const workerToTabIds: Record<WorkerTimerId, WorkerTimerId> = {};
self.addEventListener('message', e => {
const data = e.data as WorkerTimerEvent;
switch (data.type) {
case 'setTimeout':
workerToTabIds[data.id] = setTimeout(() => {
respond({ id: data.id });
delete workerToTabIds[data.id];
}, data.ms) as unknown as WorkerTimerId;
break;
case 'clearTimeout':
if (workerToTabIds[data.id]) {
clearTimeout(workerToTabIds[data.id]);
delete workerToTabIds[data.id];
}
break;
case 'setInterval':
workerToTabIds[data.id] = setInterval(() => {
respond({ id: data.id });
}, data.ms) as unknown as WorkerTimerId;
break;
case 'clearInterval':
if (workerToTabIds[data.id]) {
clearInterval(workerToTabIds[data.id]);
delete workerToTabIds[data.id];
}
break;
}
});