sainture
12/15/2016 - 8:37 PM

web worker

web worker

/*
A web worker is a process through which you can tell a browser you have a script
that's likely to take some time and you would like it run asynchronously

-- Implemented through a messaging system
   -- you send messages to the worker
   -- worker sends messages to the "main thread" 
-- Worker doesn't have the ability to update UI

A worker is an object created using a constructor (e.g. Worker()) that runs a named JavaScript file 
— this file contains the code that will run in the worker thread; 

Worker doesn't have access to the DOM

*/

// CALLING script
var myWorker = new Worker("worker.js");

// suppose you wanted to pass a message to the worker when button1 is clicked
$("#button1").click(function() {
  myWorker.postMessage("test message");
});

// receive a message from the worker
myWorker.onmessage = function(e) {
  var msg = e.data;
}

// WORKER script - event handler when the message is received
onmessage = function(e) {
  console.log('Message received from main script');
  var workerResult = 'Result: ' + e.data;
  console.log('Posting message back to main script');
  postMessage(workerResult); // you can also send some data back to the calling script
}

// web workers can pass json / javascript objects as well
// STOPPING A WEB WORKER
  // from calling script / page
     myWorker.terminate();
  // from worker script
     close();