Java Reference
In-Depth Information
Web Workers
We saw in earlier chapters that JavaScript is a single-threaded language, meaning that only
one process can run at one time.
Web workers
allow processes to be run in the background,
adding support for concurrency in JavaScript. The idea is that any processes that could take
a long time are carried out in the background, so a website will continue to function without
fear of the dreaded “script has become unresponsive” message that occurs when a script
runs for too long, shown in
Figure 14.1
.
Figure 14.1. An unresponsive script
To get started, use the
Worker()
constructor function to create a new worker:
var worker = new Worker('task.js');
This function takes the name of another JavaScript file as an argument. In the example, this
is a file called task.js. If this file exists, it will be downloaded asynchronously. The worker
will only start once the file has finished downloading completely. If the file doesn't exist,
it will fail silently.
The variable that's assigned to the constructor function (
worker
in our example) can
now be used to refer to the worker in the main program. In the worker script (task.js), the
keyword
self
is used to refer to the worker.
Web workers use the concept of messages to communicate back and forth between the main
script and worker script. The
postMessage()
method can be used to send a message
and
start the worker working. The argument to this method can send any data to the web
worker. To post a message
to
the worker, the following code is used inside the main script:
worker.postMessage("Hello");

