Game Development Reference
In-Depth Information
Web workers
Web workers bring the ability to execute code outside the main UI thread. This thread-
like behavior allows us to perform long lasting tasks without blocking the user inter-
face. When a JavaScript task takes too long to complete, the browser displays an alert
to the user, letting the user know that the page is not responsive. Using web workers,
we can solve this problem.
There are a few restrictions with web workers that we need to keep in mind. First,
workers run outside the DOM, so any functionality related to that is not available in-
side worker threads. Also, there is no concept of shared memory with workers—any
data that is passed to and from a worker is copied into its own memory space. Finally,
any objects passed to and from a worker can contain any data types, except for func-
tions. If you attempt to pass a function to or from a worker (or an object holding a
reference to a function), the browser will throw a DataCloneError (DOM Exception
25).
On the other hand, workers are completely capable of firing XHR requests (Ajax
calls), starting other workers, and stopping other workers, including themselves. Once
a worker is terminated, it can no longer be started, similar to other threading con-
structs available in other languages such as Java.
How to use it
In this section, we'll create a sample mini application that generates prime numbers
in a worker thread. The user can input a number into the application, and the applic-
ation will return a list of primes up to that number. Those prime numbers will then be
passed back to the main application, which will then list the prime numbers back to
the user.
To get started with web workers, we must first create a separate JavaScript file that
will be run in the worker thread. The way this script will communicate with its par-
ent thread is through messages. In order to receive messages from a parent thread,
the worker needs to register a callback function that is called whenever a message is
passed to it.
self.addEventListener("message", getPrimes);
Search WWH ::




Custom Search