JSFiddle - React, Tailwind, and code Playground
by xufocoder
HTML
<script type='text/worker' id='worker'>
function delay(ms) {
const start = Date.now();
let now = start;
while (now - start < ms) {
now = Date.now();
}
}
function Processor() {
this.sum = 0;
}
Processor.prototype.calculate = function(i) {
this.sum += i;
delay(10);
}
Processor.prototype.result = function() {
return this.sum;
}
const times = 1000
const processor = new Processor();
self.addEventListener('message', (e) => {
if (e.data === 'start') {
for (let i = 1; i < times; i++) {
processor.calculate(i);
}
postMessage(
processor.result()
)
}
}, false);
</script>
JavaScript
const workerScript = document.getElementById('worker').textContent
const workerScriptBlob = new Blob([workerScript]);
const worker = new Worker(URL.createObjectURL(workerScriptBlob));
worker.postMessage('start')
worker.onmessage = (e) => {
console.log(e.data)
}