How to use web workers?

Video-tutorial: https://www.youtube.com/watch?v=VLIb-by_XUA

We need a new Worker object with the URL of the script file as a parameter.
To make the worker run we need to post a message to the worker.
To get data from the worker we use the onmessage me…


This content originally appeared on DEV Community and was authored by 101samovar

Video-tutorial: https://www.youtube.com/watch?v=VLIb-by_XUA

We need a new Worker object with the URL of the script file as a parameter.
To make the worker run we need to post a message to the worker.
To get data from the worker we use the onmessage method.

The data is in the data property of the event object.

In the worker script file we need to define the onmessage method.
The data from the main script is in the data property of the event object.

The web workers can’t be started for the local files.
So we need a web-server.
A NodeJs live-server will do.

script.js

const worker = new Worker('worker.js');

worker.postMessage('Hello!');

worker.onmessage = e => {
    console.log(e.data);
}

worker.js

onmessage = e => {
    console.log(e.data);
    postMessage('Answer');
}

👋 See you next time. Have a nice day!


This content originally appeared on DEV Community and was authored by 101samovar


Print Share Comment Cite Upload Translate Updates
APA

101samovar | Sciencx (2022-01-12T11:57:11+00:00) How to use web workers?. Retrieved from https://www.scien.cx/2022/01/12/how-to-use-web-workers/

MLA
" » How to use web workers?." 101samovar | Sciencx - Wednesday January 12, 2022, https://www.scien.cx/2022/01/12/how-to-use-web-workers/
HARVARD
101samovar | Sciencx Wednesday January 12, 2022 » How to use web workers?., viewed ,<https://www.scien.cx/2022/01/12/how-to-use-web-workers/>
VANCOUVER
101samovar | Sciencx - » How to use web workers?. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/12/how-to-use-web-workers/
CHICAGO
" » How to use web workers?." 101samovar | Sciencx - Accessed . https://www.scien.cx/2022/01/12/how-to-use-web-workers/
IEEE
" » How to use web workers?." 101samovar | Sciencx [Online]. Available: https://www.scien.cx/2022/01/12/how-to-use-web-workers/. [Accessed: ]
rf:citation
» How to use web workers? | 101samovar | Sciencx | https://www.scien.cx/2022/01/12/how-to-use-web-workers/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.