JS

SUPER SIMPLE JAVASCRIPT WORKER EXAMPLE

Create a worker.js script. Do processing on receiving data, send data back when complete.

WORKER BASIC STEPS

01

On the "main page", create a new Worker("worker.js"). Simply send data to the worker for processing and wait for response.

onmessage = (evt) => {   PROCESS ON RECEIVE DATA   var res = +evt.data.a + +evt.data.b;

WORKER SCRIPT

02

  RESPOND BACK WITH RESULTS   postMessage(res); };   OPTIONAL - HANDLE ERRORS   onerror = (err) => { console.log(err); } };

CREATE WORKER var work = new Worker("worker.js");   ON WORKER RESPONSE (RESULTS) work.onmessage = (evt) =>   { console.log(evt.data); };

"MAIN PAGE" WORKER

03

OPTIONAL - HANDLE ERRORS work.onerror = (err) => { console.log(err); }   SEND DATA TO WORKER work.postMessage({ a: 9, b: 8 });