25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Using Timers<br />

CHAPTER 8 ■ USING THE <strong>HTML</strong>5 WEB WORKERS API<br />

Although <strong>HTML</strong>5 Web Workers cannot access the window object, they can make use of the full JavaScript<br />

timing API, typically found on the global window:<br />

var t = setTimeout(postMessage, 2000, "delayed message");<br />

Simple Example Code<br />

For completeness, Listings 9-2 and 9-3 show the code for the simple page and the Web Worker<br />

JavaScript file.<br />

Listing 8-2. Simple <strong>HTML</strong> Page that calls an <strong>HTML</strong>5 Web Worker<br />

<br />

Simple <strong>HTML</strong>5 Web Workers Example<br />

<br />

Simple <strong>HTML</strong>5 Web Workers Example<br />

Your browser does not support <strong>HTML</strong>5 Web Workers.<br />

Stop Task<br />

Post a Message<br />

<br />

function stopWorker() {<br />

worker.terminate();<br />

}<br />

function messageHandler(e) {<br />

console.log(e.data);<br />

}<br />

function errorHandler(e) {<br />

console.warn(e.message, e);<br />

}<br />

function loadDemo() {<br />

if (typeof(Worker) !== "undefined") {<br />

document.getElementById("support").inner<strong>HTML</strong> =<br />

"Excellent! Your browser supports <strong>HTML</strong>5 Web Workers";<br />

worker = new Worker("echoWorker.js");<br />

worker.addEventListener("message", messageHandler, true);<br />

worker.addEventListener("error", errorHandler, true);<br />

199

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!