Skip to content

Instantly share code, notes, and snippets.

@samuelcolvin
Last active May 1, 2024 14:58
Show Gist options
  • Save samuelcolvin/0a3c6545c50ae0ca2440f891d0631035 to your computer and use it in GitHub Desktop.
Save samuelcolvin/0a3c6545c50ae0ca2440f891d0631035 to your computer and use it in GitHub Desktop.
<h1>Web worker demo</h1>
<h3>Write Code:</h3>
<textarea id="code" rows="10" cols="80">return "hello world";</textarea>
<button id="run">Run</button>
<h3>Output:</h3>
<pre id="output"></pre>
<script>
const code = document.getElementById('code');
const run = document.getElementById('run');
const output = document.getElementById('output');
const worker = new Worker('worker.js');
run.addEventListener('click', function() {
output.textContent = '';
worker.postMessage(code.value);
});
worker.addEventListener('message', function(e) {
console.log(e.data);
if (e.data.result) {
output.textContent += `Result: ${e.data.result}\n`
} else {
output.textContent += `Error: ${e.data.error}\n`;
}
});
</script>
onmessage = function(e) {
console.log('Message received from main script', e);
const code = e.data;
console.log('running code:', {code});
eval(`(async () => { ${code} })()`).then((result) => {
console.log('code result:', result);
postMessage({result: JSON.stringify(result)});
}).catch((error) => {
console.error('code error:', error);
postMessage({error: JSON.stringify(error.toString())});
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment