Skip to content

Commit

Permalink
Fix race condition in webworker logic (hopefully)
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielSherlock authored and lpil committed Jan 23, 2024
1 parent 2935d24 commit ba9abad
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
16 changes: 11 additions & 5 deletions static/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ function debounce(fn, delay) {
};
}

let workerWorking = false;
let workerWorking = true;
let queuedWork = undefined;
const worker = new Worker("/worker.js", { type: "module" });

Expand All @@ -73,16 +73,17 @@ function sendToWorker(code) {
queuedWork = code;
return;
}
workerWorking = true;
worker.postMessage(code);
}

worker.onmessage = (event) => {
// Handle the result of the compilation and execution
const result = event.data;
clearOutput();
if (!result.initialReadyMessage) clearOutput();
if (result.log) appendOutput(result.log, "log");
if (result.error) appendOutput(result.error, "error");
for (const warning of result.warnings) {
for (const warning of result.warnings ?? []) {
appendOutput(warning, "warning");
}

Expand All @@ -92,5 +93,10 @@ worker.onmessage = (event) => {
queuedWork = undefined;
};

editor.onUpdate(debounce((code) => worker.postMessage(code), 200));
worker.postMessage(initialCode);
editor.onUpdate(debounce((code) => sendToWorker(code), 200));

// This line doesn't seem to be needed,
// because updating the editor to the initial code (line 57)
// triggers the onUpdate callback above (line 96) on my machine.
// But you might uncomment it anyway to be extra safe:
// sendToWorker(initialCode);
2 changes: 2 additions & 0 deletions static/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,5 @@ self.onmessage = async (event) => {
const result = compileEval(event.data);
postMessage(await result);
};

postMessage({initialReadyMessage: true});

0 comments on commit ba9abad

Please sign in to comment.