2. Agenda
1. Javascript – the event driven language
2. Limitations
3. Web Worker
4. Browser Support
5. Q & A
3. How does the browser execute
Javascript?
› Javascript is event-driven
› 3 main ways scripts get executed
› <script></script>
› Internal events (page load, setTimeout, etc)
› User input (click, focus, etc)
› When one of these occurs, the event gets
added to the event queue
4. The Event Loop
› The Javascript event loop looks at the
event queue periodically
› Executes event handlers/callbacks when
the queue is not empty
5. The event loop postman!
Source: http://developer.yahoo.com/blogs/ydn/posts/2010/10/understanding-
the-event-loops-and-writing-great-code-for-node-js-part-1/
7. Limitations
› Javascript is single threaded
› It can only do one thing at a time
› Most browser uses a single event queue
for Javascript and UI rendering
› While Javascript is running, no rendering
occurs
› Page becomes unresponsive
8. Web Worker
› Definition - “An API that allows Web
application authors to spawn background
workers running scripts in parallel to their
main page. This allows for thread-like
operation with message-passing as the
coordination mechanism"
9. Demo Logic Flow
Main Page Worker
Initialize worker.postMessage({‘cmd’ : ‘start’}) Start
worker loop
Show output self.postMessage(100000000) Counter reached
100000000 100000000
Show output self.postMessage(200000000) Counter reached
200000000 200000000
Show output self.postMessage(300000000) Counter reached
300000000 300000000
10. Worker Features
› Web workers only has access to a subset of JavaScript's
features
› The navigator object
› The location object (read-only)
› XMLHttpRequest
› setTimeout()/clearTimeout() and
setInterval()/clearInterval()
› Importing external scripts using the importScripts()
method
› Spawning other web workers
› In summary, you can’t modify the UI
11. Stopping a worker
› 2 ways to stop a worker
› Worker.terminate() in parent page
› close() in worker
› Once the worker is stopped, it has to be re-initialized