Skip to content

Commit 67405b9

Browse files
pyoortysmith
authored andcommitted
feat: use worker to poll tab
1 parent 1570271 commit 67405b9

File tree

1 file changed

+61
-11
lines changed

1 file changed

+61
-11
lines changed

src/grizzly/common/harness.html

Lines changed: 61 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,12 @@
1515
let close_after, limit_tmr
1616
let sub = null
1717
let time_limit = 0
18+
let worker = null
1819

1920
let grzDump = (msg) => {
2021
console.log(`[grz harness][${new Date().toUTCString()}] ${msg}\n`)
2122
}
2223

23-
let poll = () => {
24-
// poll until sub is closed
25-
// sub should be closed by either itself (test) or time limit
26-
if (!sub || sub.closed)
27-
setTimeout(main)
28-
else
29-
setTimeout(poll, 50)
30-
}
31-
3224
let setMsg = (msgStr) => {
3325
try {
3426
document.getElementById('msg').innerHTML = msgStr
@@ -37,6 +29,58 @@
3729
}
3830
}
3931

32+
let startPolling = () => {
33+
if (worker) {
34+
worker.terminate()
35+
}
36+
37+
const workerCode = `
38+
let pollInterval = null;
39+
40+
self.onmessage = function(e) {
41+
if (e.data.command === 'start') {
42+
// Start polling every 50ms
43+
if (pollInterval) clearInterval(pollInterval);
44+
pollInterval = setInterval(() => {
45+
self.postMessage({type: 'poll'});
46+
}, 50);
47+
} else if (e.data.command === 'stop') {
48+
if (pollInterval) {
49+
clearInterval(pollInterval);
50+
pollInterval = null;
51+
}
52+
}
53+
};
54+
`;
55+
56+
const blob = new Blob([workerCode], {type: 'application/javascript'})
57+
worker = new Worker(URL.createObjectURL(blob))
58+
59+
worker.onmessage = function(e) {
60+
if (e.data.type === 'poll') {
61+
// Check window status
62+
try {
63+
if (!sub || sub.closed) {
64+
grzDump('Worker poll: sub is closed, calling main()')
65+
worker.postMessage({command: 'stop'})
66+
setTimeout(main)
67+
}
68+
} catch (error) {
69+
grzDump(`Worker poll error: ${error}`)
70+
worker.postMessage({command: 'stop'})
71+
setTimeout(main, 500)
72+
}
73+
}
74+
}
75+
76+
worker.onerror = function(error) {
77+
grzDump(`Worker error: ${error}`)
78+
setTimeout(main, 500)
79+
}
80+
81+
worker.postMessage({command: 'start'})
82+
}
83+
4084
let main = () => {
4185
// if limit_tmr is set, clear it
4286
if (limit_tmr !== undefined) {
@@ -98,8 +142,7 @@
98142
}
99143
}, time_limit)
100144
}
101-
// wait for test to complete
102-
setTimeout(poll, 50)
145+
startPolling()
103146
}
104147
}
105148
}
@@ -124,6 +167,13 @@
124167
// begin iterations
125168
setTimeout(main)
126169
})
170+
171+
// Clean up worker when page unloads
172+
window.addEventListener('beforeunload', () => {
173+
if (worker) {
174+
worker.terminate()
175+
}
176+
})
127177
</script>
128178
</head>
129179
<body>

0 commit comments

Comments
 (0)