<div class="body">
  <p class="counter">Main thread count: <span id="secs">0</span></p>
  <p class="counter">Result: <span id="output">0</span></p>
  <button id="run1" type="button">Run by MAIN THREAD</button>
  <br />
  <br />
  <button id="run2" type="button">Run by WORKER</button>
  <button id="reset" type="button">Reset</button>
</div>

<script type="text/js-worker">
  var result;
  self.addEventListener('message', function (e) {
    for (var i = 0; i < 1e9; i++) {
      result = i;
    }
    // Send message back to the main script
    self.postMessage(result);
  }, false);
</script>
body {
  padding: 20px;
}

p {
  font-size: 26px;
  font-weight: bold;
}
View Compiled
const showSecsSpan = document.getElementById('secs');
const runMainThread = document.getElementById('run1');
const runWorkers = document.getElementById('run2');
const output = document.getElementById('output');
const reset = document.getElementById('reset');

let secsNum = 0;
function resetOutput () {
  output.innerHTML = 0;
}

setInterval(() => {
  secsNum++;
  showSecsSpan.innerHTML = secsNum;
}, 150);

runMainThread.addEventListener('click', () => {
  output.innerHTML = 0;
  setTimeout(()=> {
     var result;
    for (var i = 0; i < 1e9; i++) {
      result = i;
    }

    output.innerHTML = result;
  }, 1000)
});

runWorkers.addEventListener('click', () => {
  resetOutput();
  const blob = new Blob(
    Array.prototype.map.call(
      document.querySelectorAll('script[type="text\/js-worker"]'),
      function (oScript) { return oScript.textContent; }
    ),
    { type: 'text/javascript' }
  );

  // Create a new worker containing all "text/js-worker" scripts.
  var worker = new Worker(window.URL.createObjectURL(blob));// Listen for a message from the worker
  
  worker.addEventListener('message', function (e) {
    output.innerHTML = e.data;
  }, false);

  // Start the worker
  worker.postMessage('');
})

reset.addEventListener('click', () => {
  secsNum = 0;
  resetOutput();
})

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.