JSFiddle - React, Tailwind, and code Playground
HTML
<button id='start'>
Start
</button>
<div class='progress'></div> <br />
<div class='result'></div> <br />
<script id='worker' type='javascript/worker'>
// global variable holding partial solution
let temporal = 0;
// time intensive recursive function. Fibonacci is chosen as an example here.
function fibonacci(num) {
// store current number into global variable
temporal = num;
return num <= 1
? 1
: fibonacci(num - 1) + fibonacci(num - 2);
};
self.onmessage = function(e) {
// start calculation
const result = fibonacci(e.data.value);
postMessage({result});
}
setInterval(function() {
// post temporal solution in interval
postMessage({progress: temporal});
}, 500);
</script>
JavaScript
document.getElementById('start').onclick = function() {
// Web workers must exist in a seperate file or in seperate script tags as above
// A blob allows us to gather data from elsewhere on the page
var blob = new Blob([document.getElementById('worker').textContent]);
// We must call the Worker as a URL which is why we must gather the blob from above
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = (e) => { // All messages from the worker must be dealt with like this
if (e.data.progress !== undefined) {
console.log('progress msg received')
document.getElementsByClassName('progress')[0].innerHTML = e.data.progress;
} else {
console.log('result msg received')
console.log(e.data)
document.getElementsByClassName('result')[0].innerHTML = e.data.result;
}
};
// Web workers are kicked off usually with a Post Message as here
document.getElementsByClassName('progress')[0].innerHTML = '';
document.getElementsByClassName('result')[0].innerHTML = '';
console.log('starting calculation');
worker.postMessage({ // initiate a message to a web worker
'value': 42,
});
}