1 |
|
2 |
|
3 |
|
4 | let timeoutHandler;
|
5 | const timeoutCallbacks = {};
|
6 |
|
7 |
|
8 |
|
9 | const timeoutCallbacksCb = {};
|
10 | let timerId = 0;
|
11 | function createHandlerAndGetId() {
|
12 | if (!timeoutHandler) {
|
13 | timeoutHandler = new android.os.Handler(android.os.Looper.myLooper());
|
14 | }
|
15 | timerId++;
|
16 | return timerId;
|
17 | }
|
18 | export function setTimeout(callback, milliseconds = 0, ...args) {
|
19 |
|
20 | milliseconds += 0;
|
21 | const id = createHandlerAndGetId();
|
22 | const invoke = () => callback(...args);
|
23 | const zoneBound = zonedCallback(invoke);
|
24 | const runnable = new java.lang.Runnable({
|
25 | run: () => {
|
26 | zoneBound();
|
27 | if (timeoutCallbacks[id]) {
|
28 | delete timeoutCallbacks[id];
|
29 | delete timeoutCallbacksCb[id];
|
30 | }
|
31 | },
|
32 | });
|
33 | if (!timeoutCallbacks[id]) {
|
34 | timeoutCallbacks[id] = runnable;
|
35 | timeoutCallbacksCb[id] = callback;
|
36 | }
|
37 | timeoutHandler.postDelayed(runnable, long(milliseconds));
|
38 | return id;
|
39 | }
|
40 | export function clearTimeout(id) {
|
41 | const index = id;
|
42 | if (timeoutCallbacks[index]) {
|
43 | timeoutHandler.removeCallbacks(timeoutCallbacks[index]);
|
44 | delete timeoutCallbacks[index];
|
45 | delete timeoutCallbacksCb[index];
|
46 | }
|
47 | }
|
48 | export function setInterval(callback, milliseconds = 0, ...args) {
|
49 |
|
50 | milliseconds += 0;
|
51 | const id = createHandlerAndGetId();
|
52 | const handler = timeoutHandler;
|
53 | const invoke = () => callback(...args);
|
54 | const zoneBound = zonedCallback(invoke);
|
55 | const startOffset = milliseconds > 0 ? Date.now() % milliseconds : 0;
|
56 | function nextCallMs() {
|
57 | return milliseconds > 0 ? milliseconds - ((Date.now() - startOffset) % milliseconds) : milliseconds;
|
58 | }
|
59 | const runnable = new java.lang.Runnable({
|
60 | run: () => {
|
61 | zoneBound();
|
62 | if (timeoutCallbacks[id]) {
|
63 | handler.postDelayed(runnable, long(nextCallMs()));
|
64 | }
|
65 | },
|
66 | });
|
67 | if (!timeoutCallbacks[id]) {
|
68 | timeoutCallbacks[id] = runnable;
|
69 | timeoutCallbacksCb[id] = callback;
|
70 | }
|
71 | timeoutHandler.postDelayed(runnable, long(nextCallMs()));
|
72 | return id;
|
73 | }
|
74 | export const clearInterval = clearTimeout;
|
75 |
|
\ | No newline at end of file |