UNPKG

2.53 kBJavaScriptView Raw
1/**
2 * Android specific timer functions implementation.
3 */
4let timeoutHandler;
5const timeoutCallbacks = {};
6// this is needed to keep a strong reference to the callback
7// currently fixes a race condition in V8 with the android runtime implementation of WeakRef
8// there are fixes in the android runtime that will remove the need for this
9const timeoutCallbacksCb = {};
10let timerId = 0;
11function createHandlerAndGetId() {
12 if (!timeoutHandler) {
13 timeoutHandler = new android.os.Handler(android.os.Looper.myLooper());
14 }
15 timerId++;
16 return timerId;
17}
18export function setTimeout(callback, milliseconds = 0, ...args) {
19 // Cast to Number
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}
40export 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}
48export function setInterval(callback, milliseconds = 0, ...args) {
49 // Cast to Number
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}
74export const clearInterval = clearTimeout;
75//# sourceMappingURL=index.android.js.map
\No newline at end of file