Last active
May 1, 2024 14:58
Revisions
-
samuelcolvin revised this gist
May 1, 2024 . No changes.There are no files selected for viewing
-
samuelcolvin created this gist
May 1, 2024 .There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,30 @@ <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> This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,12 @@ 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())}); }) }