JSFiddle - React, Tailwind, and code Playground
JavaScript
var worker = null;
// check if Worker API is available in this browser
if(typeof(Worker)==="undefined") {
document.getElementById("result").innerHTML="Your browser does not support Workers.";
return;
}
/**
* This function is run by the worker.
*/
var workerCode = function() {
var runSomeOtherCode = function() {
var x = 0;
for (var i = 0; i < 1000000000; ++i) {
x += i;
}
postMessage("computed: " + x);
};
// repeatedly count up a single number and send it back to window
var doStuff = function(scriptId) {
postMessage("start"); // signal that script started
setTimeout((function(scriptId) { return function() { postMessage("stop: " + scriptId); };})(scriptId), 0); // signal that script stopped
scriptId = null;
runSomeOtherCode();
};
// call postNumber on worker start
onmessage = function(e) { doStuff(e.data); };
// FYI: window is undefined here
// console.log(typeof(window));
};
/**
* Starts the worker.
*/
var startWorker = function() {
if (worker) return;
// the code in the form of a string
//var code = document.getElementById("workercode").innerHTML;
var code = "(" + workerCode + ")();";
// Obtain a blob URL reference to our virtual worker 'file'.
var blob = new Blob([code]);
var blobURL = window.URL.createObjectURL(blob);
worker = new Worker(blobURL);
worker.postMessage(1337); // Start the worker with secret key
worker.onmessage = function (event) {
document.getElementById("result").innerHTML += event.data + "<br>";
};
};
/**
* Stops the worker.
*/
var stopWorker = function() {
if (!worker) return;
worker.terminate();
worker = null;
};
startWorker();