Clean up timeout in waitForOnline

This commit is contained in:
Evan Hahn 2021-11-01 13:38:26 -05:00 committed by GitHub
parent 8477841fd6
commit 9ea8a456f2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -14,6 +14,8 @@ export function waitForOnline(
return; return;
} }
let timeoutId: undefined | ReturnType<typeof setTimeout>;
const listener = () => { const listener = () => {
cleanup(); cleanup();
resolve(); resolve();
@ -21,12 +23,15 @@ export function waitForOnline(
const cleanup = () => { const cleanup = () => {
onlineEventTarget.removeEventListener('online', listener); onlineEventTarget.removeEventListener('online', listener);
if (typeof timeoutId === 'number') {
clearTimeout(timeoutId);
}
}; };
onlineEventTarget.addEventListener('online', listener); onlineEventTarget.addEventListener('online', listener);
if (timeout !== undefined) { if (timeout !== undefined) {
setTimeout(() => { timeoutId = setTimeout(() => {
cleanup(); cleanup();
reject(new Error('waitForOnline: did not come online in time')); reject(new Error('waitForOnline: did not come online in time'));
}, timeout); }, timeout);