Skip to content

Instantly share code, notes, and snippets.

@devdays
Created November 30, 2014 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devdays/7c0d084249dd43b50712 to your computer and use it in GitHub Desktop.
Save devdays/7c0d084249dd43b50712 to your computer and use it in GitHub Desktop.
Web Worker Two Way Communication -HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<div>
<button onclick="sayHello()">Say HI</button>
<button onclick="unknownCmd()">Send unknown command</button>
<button onclick="stop()">Stop worker</button>
</div>
<div>
<output id="workermessage"></output>
</div>
<script>
function sayHello() {
worker.postMessage({ 'cmd': 'start', 'msg': 'Hello' });
}
function stop() {
// Calling worker.terminate() from this script would also stop the worker.
worker.postMessage({ 'cmd': 'stop', 'msg': 'Bye' });
}
function unknownCmd() {
worker.postMessage({ 'cmd': 'notsupported', 'msg': '???' });
}
var worker = new Worker('3-TwoWay.js');
worker.addEventListener('message', function (e) {
document.getElementById('workermessage').textContent = e.data;
}, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment