SlideShare a Scribd company logo
Responsive Interfaces Nicholas C. Zakas Principal Front-end Engineer, Yahoo! Homepage Bayjax – April 13, 2010
The UI Thread Two jobs: Draw UI updates Execute JavaScript Only one job can happen at a time Jobs are added to a queue if they are generated while the UI thread is busy
<button id=&quot;btn&quot; style=&quot;font-size: 30px; padding: 0.5em 1em&quot;>Click Me</button> <script type=&quot;text/javascript&quot;> window.onload =  function (){ document.getElementById(&quot;btn&quot;).onclick =  function (){ //do something }; }; </script>
When Clicked A button UI change job is created Draws the button in the down state A JavaScript execution job is created The onclick event handler A button UI change job is created Draws the button in the up state
Before Click Start UI Thread UI Queue
When Clicked Start UI Thread onclick UI Queue
When Clicked Start UI Thread onclick UI Queue
When Clicked onclick Start UI Thread UI Queue
When Clicked onclick Start UI Thread UI Queue
No UI updates while JavaScript is executing!
Why?
JavaScript May Cause UI Update <button id=&quot;btn&quot; style=&quot;font-size: 30px; padding: 0.5em 1em&quot;>Click Me</button> <script type=&quot;text/javascript&quot;> window.onload =  function (){ document.getElementById(&quot;btn&quot;).onclick =  function (){ var div = document.createElement(“div”); div.className = “tip”; div.innerHTML = “You clicked me!”; document.body.appendChild(div); }; }; </script>
UI updates must use the latest info available
Long-running JavaScript = Unresponsive UI
Runaway Script Timer Designed to prevent the browser from affecting the operating system Limits the amount of time a script is allowed to execute Two types of limits: Execution time Number of statements Always pops up a scary dialog to the user Exception: Opera has no runaway timer
Internet Explorer
Firefox
Safari
Chrome
Runaway Script Timer Limits Internet Explorer: 5 million statements Firefox: 10 seconds Safari: 5 seconds Chrome: Unknown, hooks into normal crash control mechanism Opera: none
How long is too long?
How Long Is Too Long? “ 0.1 second [100ms] is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.” - Jakob Nielsen
Translation: JavaScript should not execute for longer than 100ms to ensure responsive UI
Recommendation: Limit JavaScript to no more than 50ms at a time
function  processArray(items, process, callback){ for  ( var  i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
Timers to the rescue!
JavaScript Timers Created using setTimeout() Schedules a new JavaScript execution job for some time in the future When the delay is up, the job is added to the UI queue Note: This does not guarantee execution after the delay, just that the job is added to the UI queue and will be executed when appropriate
JavaScript Timers For complex processing, split up into timed functionality Use timers to delay some processing for later
function  timedProcessArray(items, process, callback){ //create a clone of the original   var  todo = items.concat();  setTimeout(function(){ var  start = +new Date(); do  { process(todo.shift()); }  while  (todo.length > 0 &&  (+ new  Date() - start < 50)); if  (todo.length > 0){ setTimeout(arguments.callee, 25); }  else  { callback(items); } }, 25); }
Web Workers to the rescue!
 
Web Workers Asynchronous JavaScript execution Execution happens in a separate process Not on the UI thread = no UI delays Data-driven API Data is serialized when sending data into or out of Worker No access to DOM, BOM Completely separate execution environment
//in page var  worker =  new  Worker(&quot;code.js&quot;); worker.onmessage =  function (event){ alert(event.data); }; worker.postMessage(&quot;Nicholas&quot;); //in code.js self.onmessage =  function (event){ self.postMessage(&quot;Hello, &quot; + event.data + &quot;!&quot;); };
Web Workers Support Firefox 3.5 Safari 4 Chrome 4
Summary UI thread is used both for JavaScript execution and UI updates UI cannot be updated while JavaScript is executing Keep JavaScript execution to 50ms – use timers and/or web workers to offload processing
Etcetera My blog:  www.nczonline.net My email: [email_address] Twitter: @slicknet

More Related Content

What's hot

Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
Nicholas Zakas
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
Nicholas Zakas
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
Steve Souders
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas
 
Cache is King
Cache is KingCache is King
Cache is King
Steve Souders
 
jQuery 1.9 and 2.0 - Present and Future
jQuery 1.9 and 2.0 - Present and FuturejQuery 1.9 and 2.0 - Present and Future
jQuery 1.9 and 2.0 - Present and Future
Richard Worth
 
Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas
 
Testing Mobile JavaScript
Testing Mobile JavaScriptTesting Mobile JavaScript
Testing Mobile JavaScript
jeresig
 
Using Modern Browser APIs to Improve the Performance of Your Web Applications
Using Modern Browser APIs to Improve the Performance of Your Web ApplicationsUsing Modern Browser APIs to Improve the Performance of Your Web Applications
Using Modern Browser APIs to Improve the Performance of Your Web Applications
Nicholas Jansma
 
Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service Worker
Chang W. Doh
 
Hyperlight Websites - Chris Zacharias
Hyperlight Websites - Chris ZachariasHyperlight Websites - Chris Zacharias
Hyperlight Websites - Chris Zacharias
Christopher Zacharias
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
Nicholas Zakas
 
Learning from the Best jQuery Plugins
Learning from the Best jQuery PluginsLearning from the Best jQuery Plugins
Learning from the Best jQuery Plugins
Marc Grabanski
 
Web versus Native: round 1!
Web versus Native: round 1!Web versus Native: round 1!
Web versus Native: round 1!
Chris Mills
 
Empowering the "mobile web"
Empowering the "mobile web"Empowering the "mobile web"
Empowering the "mobile web"
Chris Mills
 
Forensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsForensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance Investigations
Nicholas Jansma
 
Debugging IE Performance Issues with xperf, ETW and NavigationTiming
Debugging IE Performance Issues with xperf, ETW and NavigationTimingDebugging IE Performance Issues with xperf, ETW and NavigationTiming
Debugging IE Performance Issues with xperf, ETW and NavigationTiming
Nicholas Jansma
 
Node JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web AppNode JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web App
Edureka!
 

What's hot (20)

Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
 
High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
 
High Performance JavaScript 2011
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
 
High Performance Snippets
High Performance SnippetsHigh Performance Snippets
High Performance Snippets
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
 
Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
 
Cache is King
Cache is KingCache is King
Cache is King
 
jQuery 1.9 and 2.0 - Present and Future
jQuery 1.9 and 2.0 - Present and FuturejQuery 1.9 and 2.0 - Present and Future
jQuery 1.9 and 2.0 - Present and Future
 
Browser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
 
Testing Mobile JavaScript
Testing Mobile JavaScriptTesting Mobile JavaScript
Testing Mobile JavaScript
 
Using Modern Browser APIs to Improve the Performance of Your Web Applications
Using Modern Browser APIs to Improve the Performance of Your Web ApplicationsUsing Modern Browser APIs to Improve the Performance of Your Web Applications
Using Modern Browser APIs to Improve the Performance of Your Web Applications
 
Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service Worker
 
Hyperlight Websites - Chris Zacharias
Hyperlight Websites - Chris ZachariasHyperlight Websites - Chris Zacharias
Hyperlight Websites - Chris Zacharias
 
Mobile Web Speed Bumps
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
 
Learning from the Best jQuery Plugins
Learning from the Best jQuery PluginsLearning from the Best jQuery Plugins
Learning from the Best jQuery Plugins
 
Web versus Native: round 1!
Web versus Native: round 1!Web versus Native: round 1!
Web versus Native: round 1!
 
Empowering the "mobile web"
Empowering the "mobile web"Empowering the "mobile web"
Empowering the "mobile web"
 
Forensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsForensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance Investigations
 
Debugging IE Performance Issues with xperf, ETW and NavigationTiming
Debugging IE Performance Issues with xperf, ETW and NavigationTimingDebugging IE Performance Issues with xperf, ETW and NavigationTiming
Debugging IE Performance Issues with xperf, ETW and NavigationTiming
 
Node JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web AppNode JS Express: Steps to Create Restful Web App
Node JS Express: Steps to Create Restful Web App
 

Viewers also liked

Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas
 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable Performance
Nicholas Zakas
 
Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)
Nicholas Zakas
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Nicholas Zakas
 
Speed Up Your JavaScript
Speed Up Your JavaScriptSpeed Up Your JavaScript
Speed Up Your JavaScript
Nicholas Zakas
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Nicholas Zakas
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
Nicholas Zakas
 

Viewers also liked (7)

Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
 
JavaScript Variable Performance
JavaScript Variable PerformanceJavaScript Variable Performance
JavaScript Variable Performance
 
Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)
 
Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)Enterprise JavaScript Error Handling (Ajax Experience 2008)
Enterprise JavaScript Error Handling (Ajax Experience 2008)
 
Speed Up Your JavaScript
Speed Up Your JavaScriptSpeed Up Your JavaScript
Speed Up Your JavaScript
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
 

Similar to Responsive interfaces

Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)
Mikkel Flindt Heisterberg
 
Setting UIAutomation free with Appium
Setting UIAutomation free with AppiumSetting UIAutomation free with Appium
Setting UIAutomation free with Appium
Dan Cuellar
 
Web workers | JavaScript | HTML API
Web workers | JavaScript | HTML APIWeb workers | JavaScript | HTML API
Web workers | JavaScript | HTML API
pcnmtutorials
 
Setting Apple's UI Automation Free with Appium
Setting Apple's UI Automation Free with AppiumSetting Apple's UI Automation Free with Appium
Setting Apple's UI Automation Free with Appium
mobiletestsummit
 
Qtp 9.2 examples
Qtp 9.2 examplesQtp 9.2 examples
Qtp 9.2 examples
medsherb
 
Claim Academy Intro to Programming
Claim Academy Intro to ProgrammingClaim Academy Intro to Programming
Claim Academy Intro to Programming
Alex Pearson
 
PAC 2019 virtual Arjan Van Den Berg
PAC 2019 virtual Arjan Van Den Berg  PAC 2019 virtual Arjan Van Den Berg
PAC 2019 virtual Arjan Van Den Berg
Neotys
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Julien Lecomte
 
jQuery
jQueryjQuery
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
Ivano Malavolta
 
Developing Async Sense
Developing Async SenseDeveloping Async Sense
Developing Async Sense
Nemanja Stojanovic
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
David Barreto
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
AnamikaRai59
 
The fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose ReactThe fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose React
Oliver N
 
JavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern ImplementationJavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern Implementation
davejohnson
 
3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace
Frank Krueger
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
Karl-Henry Martinsson
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
tutorialsruby
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
tutorialsruby
 

Similar to Responsive interfaces (20)

Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)Plug yourself in and your app will never be the same (1 hr edition)
Plug yourself in and your app will never be the same (1 hr edition)
 
Setting UIAutomation free with Appium
Setting UIAutomation free with AppiumSetting UIAutomation free with Appium
Setting UIAutomation free with Appium
 
Web workers | JavaScript | HTML API
Web workers | JavaScript | HTML APIWeb workers | JavaScript | HTML API
Web workers | JavaScript | HTML API
 
Setting Apple's UI Automation Free with Appium
Setting Apple's UI Automation Free with AppiumSetting Apple's UI Automation Free with Appium
Setting Apple's UI Automation Free with Appium
 
Qtp 9.2 examples
Qtp 9.2 examplesQtp 9.2 examples
Qtp 9.2 examples
 
Claim Academy Intro to Programming
Claim Academy Intro to ProgrammingClaim Academy Intro to Programming
Claim Academy Intro to Programming
 
PAC 2019 virtual Arjan Van Den Berg
PAC 2019 virtual Arjan Van Den Berg  PAC 2019 virtual Arjan Van Den Berg
PAC 2019 virtual Arjan Van Den Berg
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
jQuery
jQueryjQuery
jQuery
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Developing Async Sense
Developing Async SenseDeveloping Async Sense
Developing Async Sense
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance MeetupAngular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
 
The fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose ReactThe fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose React
 
JavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern ImplementationJavaScript and DOM Pattern Implementation
JavaScript and DOM Pattern Implementation
 
3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace3 Mobile App Dev Problems - Monospace
3 Mobile App Dev Problems - Monospace
 
AD102 - Break out of the Box
AD102 - Break out of the BoxAD102 - Break out of the Box
AD102 - Break out of the Box
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
 
orcreatehappyusers
orcreatehappyusersorcreatehappyusers
orcreatehappyusers
 

More from Nicholas Zakas

The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
Nicholas Zakas
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Nicholas Zakas
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
Nicholas Zakas
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
Nicholas Zakas
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
Nicholas Zakas
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
Nicholas Zakas
 
The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3
Nicholas Zakas
 

More from Nicholas Zakas (8)

The Pointerless Web
The Pointerless WebThe Pointerless Web
The Pointerless Web
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
 
Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 
Scalable JavaScript Application Architecture
Scalable JavaScript Application ArchitectureScalable JavaScript Application Architecture
Scalable JavaScript Application Architecture
 
Extreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI CompressorExtreme JavaScript Compression With YUI Compressor
Extreme JavaScript Compression With YUI Compressor
 
Maintainable JavaScript
Maintainable JavaScriptMaintainable JavaScript
Maintainable JavaScript
 
The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3The New Yahoo! Homepage and YUI 3
The New Yahoo! Homepage and YUI 3
 

Responsive interfaces

  • 1. Responsive Interfaces Nicholas C. Zakas Principal Front-end Engineer, Yahoo! Homepage Bayjax – April 13, 2010
  • 2. The UI Thread Two jobs: Draw UI updates Execute JavaScript Only one job can happen at a time Jobs are added to a queue if they are generated while the UI thread is busy
  • 3. <button id=&quot;btn&quot; style=&quot;font-size: 30px; padding: 0.5em 1em&quot;>Click Me</button> <script type=&quot;text/javascript&quot;> window.onload = function (){ document.getElementById(&quot;btn&quot;).onclick = function (){ //do something }; }; </script>
  • 4. When Clicked A button UI change job is created Draws the button in the down state A JavaScript execution job is created The onclick event handler A button UI change job is created Draws the button in the up state
  • 5. Before Click Start UI Thread UI Queue
  • 6. When Clicked Start UI Thread onclick UI Queue
  • 7. When Clicked Start UI Thread onclick UI Queue
  • 8. When Clicked onclick Start UI Thread UI Queue
  • 9. When Clicked onclick Start UI Thread UI Queue
  • 10. No UI updates while JavaScript is executing!
  • 11. Why?
  • 12. JavaScript May Cause UI Update <button id=&quot;btn&quot; style=&quot;font-size: 30px; padding: 0.5em 1em&quot;>Click Me</button> <script type=&quot;text/javascript&quot;> window.onload = function (){ document.getElementById(&quot;btn&quot;).onclick = function (){ var div = document.createElement(“div”); div.className = “tip”; div.innerHTML = “You clicked me!”; document.body.appendChild(div); }; }; </script>
  • 13. UI updates must use the latest info available
  • 14. Long-running JavaScript = Unresponsive UI
  • 15. Runaway Script Timer Designed to prevent the browser from affecting the operating system Limits the amount of time a script is allowed to execute Two types of limits: Execution time Number of statements Always pops up a scary dialog to the user Exception: Opera has no runaway timer
  • 20. Runaway Script Timer Limits Internet Explorer: 5 million statements Firefox: 10 seconds Safari: 5 seconds Chrome: Unknown, hooks into normal crash control mechanism Opera: none
  • 21. How long is too long?
  • 22. How Long Is Too Long? “ 0.1 second [100ms] is about the limit for having the user feel that the system is reacting instantaneously, meaning that no special feedback is necessary except to display the result.” - Jakob Nielsen
  • 23. Translation: JavaScript should not execute for longer than 100ms to ensure responsive UI
  • 24. Recommendation: Limit JavaScript to no more than 50ms at a time
  • 25. function processArray(items, process, callback){ for ( var i=0,len=items.length; i < len; i++){ process(items[i]); } callback(); }
  • 26. Timers to the rescue!
  • 27. JavaScript Timers Created using setTimeout() Schedules a new JavaScript execution job for some time in the future When the delay is up, the job is added to the UI queue Note: This does not guarantee execution after the delay, just that the job is added to the UI queue and will be executed when appropriate
  • 28. JavaScript Timers For complex processing, split up into timed functionality Use timers to delay some processing for later
  • 29. function timedProcessArray(items, process, callback){ //create a clone of the original var todo = items.concat(); setTimeout(function(){ var start = +new Date(); do { process(todo.shift()); } while (todo.length > 0 && (+ new Date() - start < 50)); if (todo.length > 0){ setTimeout(arguments.callee, 25); } else { callback(items); } }, 25); }
  • 30. Web Workers to the rescue!
  • 31.  
  • 32. Web Workers Asynchronous JavaScript execution Execution happens in a separate process Not on the UI thread = no UI delays Data-driven API Data is serialized when sending data into or out of Worker No access to DOM, BOM Completely separate execution environment
  • 33. //in page var worker = new Worker(&quot;code.js&quot;); worker.onmessage = function (event){ alert(event.data); }; worker.postMessage(&quot;Nicholas&quot;); //in code.js self.onmessage = function (event){ self.postMessage(&quot;Hello, &quot; + event.data + &quot;!&quot;); };
  • 34. Web Workers Support Firefox 3.5 Safari 4 Chrome 4
  • 35. Summary UI thread is used both for JavaScript execution and UI updates UI cannot be updated while JavaScript is executing Keep JavaScript execution to 50ms – use timers and/or web workers to offload processing
  • 36. Etcetera My blog: www.nczonline.net My email: [email_address] Twitter: @slicknet

Editor's Notes

  1. So what have we talked about? Maintainable JavaScript is made up of four components. First is Code Conventions that describe the format of the code you’re writing. Second is Loose Coupling – keeping HTML, JavaScript, and CSS on separate layers and keeping application logic out of event handlers. Third is Programming Practices that ensure your code is readable and easily debugged. Fourth is creating a Build Process