JS

JAVASCRIPT WORKER EXAMPLE

(quick guide & example)

Create a worker.js script that will do processing on receiving data, send data back on 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.

WORKER SCRIPT

02

OPTIONAL - HANDLE ERRORS onmessageerror = e => console.error(e); onerror = e => console.error(e);

onmessage = e => {   PROCESS ON RECEIVE DATA   var res = +e.data.a + +e.data.b;     RESPOND BACK WITH RESULTS   postMessage(res); };

CREATE WORKER var w = new Worker("worker.js");

"MAIN PAGE" WORKER

03

OPTIONAL - HANDLE ERRORS w.onerror = e => console.error(e);

ON WORKER RESPONSE (RESULTS) w.onmessage = e => console.log(e.data);

SEND DATA TO WORKER w.postMessage({ a: 9, b: 8 });