Skip to content

Instantly share code, notes, and snippets.

@MatthiasKainer
Created December 16, 2022 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthiasKainer/2e09b0886ac663ee007d02e25db78b46 to your computer and use it in GitHub Desktop.
Save MatthiasKainer/2e09b0886ac663ee007d02e25db78b46 to your computer and use it in GitHub Desktop.
simple example for a CPU heavy webworker without blocking the browser
function heavyComputation(n) {
if (n <= 1) {
return n;
}
return heavyComputation(n - 1) + heavyComputation(n - 1);
}
onmessage = function (e) {
console.log('Worker: Message received from main script', e.data);
const result = heavyComputation(e.data)
for (let i = 0; i < result; i++) {
heavyComputation(e.data)
}
this.postMessage(result)
}
<!DOCTYPE html>
<html>
<head>
<title>Empty project</title>
<meta charset="utf-8">
</head>
<body>
<hello-world></hello-world>
<script type="module" src="index.ts"></script>
</body>
</html>
import { html, LitElement } from "lit";
import { pureLit, useOnce, useState } from "pure-lit";
const useWorker = <T>(el: LitElement, worker: Worker) => {
const result = useState<string | undefined>(el, undefined)
worker.onmessage = (e) => (console.log("Main: Received result:", e.data, "before", result), (result.set(e.data)))
return {
set : (data: T) => (result.set("Please wait while loading!"), worker.postMessage(data)),
get : result.get
}
}
pureLit("hello-world", (el) => {
const input = useState(el, "")
const worker = useWorker<number>(el, new Worker(new URL("data-url:./greet.js", import.meta.url)))
return html`
<input type="number" @input=${(e: InputEvent) => (input.set(e.target?.value), worker.set(e.target?.value))} .value="${input.get()}">
<p>${worker.get() ?? "Waiting for hello"}</p>
`
}, {
defaults: {
name: ""
}
})
{
"name": "worker-test",
"version": "1.0.0",
"description": "Testing web-worker",
"main": "index.js",
"scripts": {
"clean": "rm -rf dist/",
"start": "parcel index.html",
"build": "npm run clean && parcel build index.html"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@parcel/optimizer-data-url": "^2.8.2",
"@parcel/transformer-inline-string": "^2.8.2",
"parcel": "^2.8.2"
},
"dependencies": {
"lit": "^2.5.0",
"pure-lit": "^2.0.7"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment