Parcourir la source

use safer timeouts with shorter delays

Gildas il y a 7 ans
Parent
commit
2923e449b0
1 fichiers modifiés avec 33 ajouts et 4 suppressions
  1. 33 4
      lib/single-file/frame-tree/content/frame-tree.js

+ 33 - 4
lib/single-file/frame-tree/content/frame-tree.js

@@ -23,11 +23,40 @@
 this.FrameTree = this.FrameTree || (() => {
 
 	const MESSAGE_PREFIX = "__FrameTree__";
-	const TIMEOUT_INIT_REQUEST_MESSAGE = 1000;
-	const TIMEOUT_DATA_RESPONSE_MESSAGE = 1000;
+	const TIMEOUT_INIT_REQUEST_MESSAGE = 500;
+	const TIMEOUT_DATA_RESPONSE_MESSAGE = 500;
+	const TIMEOUT_STEP = 100;
 
 	const FrameTree = { getFramesData };
 
+	const timeoutIds = [];
+	const timeout = {
+		set(fn, delay) {
+			const id = timeoutIds.length;
+			let elapsedTime = 0;
+			timeoutIds[id] = setTimeout(step, 0);
+			return id;
+
+			function step() {
+				if (elapsedTime < delay) {
+					timeoutIds[id] = setTimeout(() => {
+						elapsedTime += TIMEOUT_STEP;
+						step();
+					}, TIMEOUT_STEP);
+				}
+				else {
+					fn();
+				}
+			}
+		},
+		clear(id) {
+			if (timeoutIds[id]) {
+				clearTimeout(timeoutIds[id]);
+				timeoutIds[id] = null;
+			}
+		}
+	};
+
 	let framesData, dataRequestCallbacks;
 
 	if (window == top) {
@@ -85,7 +114,7 @@ this.FrameTree = this.FrameTree || (() => {
 						options: { removeHiddenElements: options.removeHiddenElements, compressHTML: options.compressHTML }
 					}).catch(() => { /* ignored */ });
 				}
-				frameData.getDataResponseTimeout = setTimeout(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: frameData.windowId }), "*"), TIMEOUT_DATA_RESPONSE_MESSAGE);
+				frameData.getDataResponseTimeout = timeout.set(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "getDataResponse", windowId: frameData.windowId }), "*"), TIMEOUT_DATA_RESPONSE_MESSAGE);
 			});
 		}));
 		return framesData.sort((frame1, frame2) => frame2.windowId.split(".").length - frame1.windowId.split(".").length);
@@ -155,7 +184,7 @@ this.FrameTree = this.FrameTree || (() => {
 				topWindow.addEventListener("message", onMessage, false);
 			} else if (frameWindow) {
 				frameWindow.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initRequest", windowId: frameWinId, index }), "*");
-				setTimeout(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: frameWinId, index }), "*"), TIMEOUT_INIT_REQUEST_MESSAGE);
+				timeout.set(() => top.postMessage(MESSAGE_PREFIX + "::" + JSON.stringify({ method: "initResponse", framesData: [], windowId: frameWinId, index }), "*"), TIMEOUT_INIT_REQUEST_MESSAGE);
 			}
 
 			function onMessage(event) {