HTML and CSS Reference
In-Depth Information
Objective 2.5: Create a web worker process
Web workers present a way of developing multithreaded JavaScript applications. JavaScript is
a single-threaded environment. Everything run in JavaScript is queued up synchronously. This
might not be evident in most applications because the available processing power on client
computers usually far exceeds what's required by a webpage on a client computer. However,
in more intense web applications, you have seen warning messages from the browser that the
scripts are running and taking a long time to complete. In fact, these warnings give users the
option to stop running scripts on the page immediately. This type of user experience won't
have users coming back to the website. This is where the Web Worker API is useful.
This objective covers how to:
Get started with a web worker process
Create a worker process with the Web Worker API
Use a web worker
Understand web worker limitations
Configure timeouts and intervals
Getting started with a web worker process
The Web Worker API enables you to specify that pieces of work should be processed on their
own thread. Doing so has many advantages but also some pitfalls that you need to respect.
In this objective, you learn how to use the Web Worker API to take advantage of the flexibil-
ity this brings to web applications. You also learn about the disadvantages and cautions that
come with using web workers.
This objective uses the bouncing ball example to demonstrate the use of a web worker.
Listing 2-3 shows the basic code for the bouncing ball. It will be adjusted as you work through
the sections within this objective to achieve moving work to a web worker process.
LISTING 2-3 Bouncing ball
window.requestAnimFrame = (function (callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame || window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 30);
Search WWH ::

Custom Search