Skip to content

Instantly share code, notes, and snippets.

@JackHowa
Created July 28, 2019 16:11
Show Gist options
  • Save JackHowa/1640815e815852f08c83660054c3eca1 to your computer and use it in GitHub Desktop.
Save JackHowa/1640815e815852f08c83660054c3eca1 to your computer and use it in GitHub Desktop.
web-workers
(function Home(){
"use strict";
var startStopBtn;
var fibsList;
var worker;
document.addEventListener("DOMContentLoaded",ready,false);
// **********************************
function ready() {
startStopBtn = document.getElementById("start-stop-btn");
fibsList = document.getElementById("fibs");
startStopBtn.addEventListener("click",startFibs,false);
}
function renderFib(num,fib) {
var p = document.createElement("div");
p.innerText = `Fib(${num}): ${fib}`;
if (fibsList.childNodes.length > 0) {
fibsList.insertBefore(p,fibsList.childNodes[0]);
}
else {
fibsList.appendChild(p);
}
}
function startFibs() {
startStopBtn.removeEventListener("click",startFibs,false);
startStopBtn.addEventListener("click",stopFibs,false);
startStopBtn.innerText = "Stop";
fibsList.innerHTML = "";
// instantiate a new worker
// all browsers supporting, except opera mini
// give url for js fle
worker = new Worker("/js/worker.js");
worker.addEventListener('message', onMessage);
worker.postMessage({ start: true });
}
function stopFibs() {
startStopBtn.removeEventListener("click",stopFibs,false);
startStopBtn.addEventListener("click",startFibs,false);
startStopBtn.innerText = "Start";
// how to stop a worker
worker.terminate();
}
function onMessage(evt) {
// get data property which is the actual event
console.log(evt.data);
renderFib(evt.data.idx, evt.data.fib)
}
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web Workers</title>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<header>
<h1>Web Workers</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
</ul>
</nav>
</header>
<main>
<p>
Let's explore Web Workers together.
</p>
<p>
Fibonacci Numbers: <button type="button" id="start-stop-btn">Start</button>
</p>
<div id="fibs"></div>
</main>
<script src="/js/home.js"></script>
</body>
</html>
"use strict";
var curFib = 0;
// send a message back to the page
self.postMessage("Hello from the web worker")
self.onmessage = onMessage;
// **********************************
function onMessage(evt) {
getNextFib();
}
function getNextFib() {
var fibNum = fib(curFib);
// post a message to the page with what we've done
self.postMessage({ fib: fibNum, idx: curFib });
curFib++;
// then we want to get next fib
// update with fib idx
// could wait on the next event loop
setTimeout(getNextFib(), 0);
}
function fib(n) {
if (n < 2) {
return n;
}
return fib(n-1) + fib(n-2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment