ESThread

Modern worker threading library

by MKGaru

HTML

<script src="https://unpkg.com/esthread"></script>
<div>
  <button onclick="run()">Calculate fibonacci number on worker threads.</button>
</div>
<textarea rows="5" cols="40">If use main thread, all ui will be freeze. (for example can not edit here)</textarea>

<div id="console"></div>

<a href="https://jsfiddle.net/MKGaru/toesLcan/" target="_blank">with main thread example.</a>

CSS

#console {
  border: solid 1px #ccc;
  overflow: auto;
  height: 10em;
  font-size: 0.8em;
  white-space: pre-wrap;
}

JavaScript

// blocking slow function.
function fibonacci(n){
  return n<2 ? n : ( fibonacci(n-1) + fibonacci(n-2) )
}

function run(){
  const [thread3a,thread3b,thread3c] = new Thread(fibonacci).clone(3)
  thread3a.once(38).then((result)=>console.log(result))
  thread3b.once(40).then((result)=>console.log(result))
  thread3c.once(42).then((result)=>console.log(result))
}

const console = {
  log: function(message){ document.querySelector('#console').innerHTML += message+'\r\n' }
}