From fa65ab351293fa6af882479e0fad6aaca3152569 Mon Sep 17 00:00:00 2001 From: siikamiika Date: Sun, 22 Mar 2020 12:45:58 +0200 Subject: refactor getTemporaryListenerResult timeout --- ext/fg/js/frame-offset-forwarder.js | 3 ++- ext/mixed/js/core.js | 23 +++++++++++++---------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/ext/fg/js/frame-offset-forwarder.js b/ext/fg/js/frame-offset-forwarder.js index 781a9018..38fc0b03 100644 --- a/ext/fg/js/frame-offset-forwarder.js +++ b/ext/fg/js/frame-offset-forwarder.js @@ -50,7 +50,8 @@ class FrameOffsetForwarder { if (action === 'frameOffset' && isObject(params) && params.uniqueId === uniqueId) { resolve(params); } - } + }, + 5000 ); window.parent.postMessage({ diff --git a/ext/mixed/js/core.js b/ext/mixed/js/core.js index f21bac23..616f48b8 100644 --- a/ext/mixed/js/core.js +++ b/ext/mixed/js/core.js @@ -312,8 +312,7 @@ const yomichan = (() => { this.trigger('orphaned', {error}); } - getTemporaryListenerResult(eventHandler, userCallback, timeout=30000) { - let resolved = false; + getTemporaryListenerResult(eventHandler, userCallback, timeout=null) { let resolve; let reject; const listenerPromise = new Promise((_resolve, _reject) => { @@ -323,20 +322,24 @@ const yomichan = (() => { if (eventHandler === chrome.runtime.onMessage) { const runtimeMessageCallback = ({action, params}, sender, sendResponse) => { + let timeoutId = null; + if (timeout !== null) { + timeoutId = window.setTimeout(() => { + timeoutId = null; + reject(new Error(`Listener timed out in ${timeout} ms`)); + eventHandler.removeListener(runtimeMessageCallback); + }, timeout); + } + const cleanupResolve = (value) => { - resolved = true; + if (timeoutId !== null) { + window.clearTimeout(timeoutId); + } eventHandler.removeListener(runtimeMessageCallback); sendResponse(); resolve(value); }; - setTimeout(() => { - if (!resolved) { - reject(new Error(`Listener timed out in ${timeout} ms`)); - eventHandler.removeListener(runtimeMessageCallback); - } - }, timeout); - userCallback({action, params}, {resolve: cleanupResolve, sender}); }; -- cgit v1.2.3