SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Making the most of your
single thread

Titanium - Fundamentals
Congrats!
!

Your app is in the
hands of the public!
Your users click on buttons,
open windows, and at some
point someone touches a
button that results in…
Absolutely
Nothing.
He tries touching it three
times, before deciding, after
a mere few seconds, that
your app has crashed.

!

He kills your app.
Had he waited
for ‘but’ 5
seconds..
.. he would have noticed
three windows opening in
rapid succession. Three
identical windows, as he
would observe when using
the ‘back’-button.
What did you do wrong?
•

There’s no loading indicator showing

•

There is no mechanic in place to prevent additional
windows from opening
What did you do wrong?
•

There’s no loading indicator showing

•

There is no mechanic in place to prevent additional
windows from opening

•

But more important: You blocked the UI far too long!

You did not make the best use of your single
thread!
Ronald Treur
Co-founder Snowciety

!
Freelance developer

!
2.5 yrs Titanium experience

!
@ronaldtreur

ronald@funcracker.net
Making the Most of Your Single Thread
•

Threads & Threading

•

How it works in Native & Titanium

•

Javascript call stack example

•

Underscore - Defer
Thread
The smallest subset of a
process that could be
independently handled
by the OS.

or
The smallest piece of
code, that could be
executed independently
from the rest of the
code.
Thread
Process

Threads
Threading
•

Multi-threaded: 

- Threads (can) run in parallel, meaning:

- Multiple pieces of code can execute at the same time.
#1
#2

!

#3
#4

!

•

#1

Single-threaded:

- Threads can only run serially, meaning:

- Only one piece of code can execute at a time.
#2

#3
How Native works

Main
Thread

Thread
#1

Thread
#2

Thread
#3

Thread
#4

Thread
#..
How Titanium works

UI

JS

Debug

Main
Thread

Thread
#1

Thread
#2

Thread
#3

Thread
#4
How your app works

JS

Thread
#1
Thread Safe
Javascript is by definition NOT thread safe.
•

If multiple threads would be able to access and change
the same object/variable, a race condition might occur.

•

aka: the outcome of a piece of code would be
unpredictable.
Single Threaded
Javascript is by definition NOT thread safe. Thus it is, by
nature, single threaded.
•

Timers are not part of Javascript, they are part of the
JS engine (Rhino, V8, JavaScriptCore)

•

Timers allow for asynchronous delays, but code
execution remains single threaded.

•

When a timer expires, or an event fires, the resulting
execution is queued.
Call Stack

ms

‘events’

0

foo()

foo()

foo()
0

10

20

ms

30

40

50
Call Stack

ms

‘events’

0
0
0

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)

nerf()

foo()

bar()

bar()

bar()

bar()

bar()

30

40

50

foo()
0

10

20

ms
Call Stack

[click]

foo()

‘events’

0
0
0
6

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)
Button clicked

nerf()

bar()

foo()
0

ms

10

bar()

bar()

bar()

bar()

30

40

50

click
handler
20

ms
Call Stack

ms

In Titanium the queue is
FIFO (first in, first out).

[click]

foo()

0
0
0
6
10

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)
Button clicked
Interval fires

nerf()

bar()

foo()
0

‘events’

10

bar()

bar()

bar()

bar()

40

50

click
bar()
handler
20

ms

30
Call Stack

[click]

foo()

‘events’

0
0
0
6
10
20

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)
Button clicked
Interval fires
Interval & Timer fire

nerf()

bar()

foo()
0

ms

10

bar()

bar()

bar()

bar()

click
bar() nerf()
handler
20

ms

30

40

50
Call Stack

ms

The interval at 20ms is
ignored, an execution is
already scheduled.
[click]

foo()

0
0
0
6
10
20

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)
Button clicked
Interval fires
Interval & Timer fire

nerf()

bar()

foo()
0

‘events’

10

bar()

bar()

bar()

bar()

click
bar() nerf()
handler
20

ms

30

40

50
Call Stack

ms

The interval at 30ms is
queued, since no
execution is scheduled.
[click]

foo()

0
0
0
6
10
20
30

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)
Button clicked
Interval fires
Interval & Timer fire
Interval fires

nerf()

bar()

foo()
0

‘events’

10

bar()

bar()

bar()

bar()

click
bar() nerf() bar()
handler
20

ms

30

40

50
Call Stack

ms

‘events’

nerf()

0
0
0
6
10
20
30
40

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)
Button clicked
Interval fires
Interval & Timer fire
Interval fires
Interval fires

bar()

bar()

Interval at 40ms is
ignored.

[click]

foo()

bar()

foo()
0

10

bar()

bar()

click
bar() nerf() bar()
handler
20

ms

30

40

50
Call Stack

ms

Interval at 50ms is the first
to execute at the correct
time (though 2 executions
were dropped).
[click]

foo()

nerf()

bar()

foo()
0

10

bar()

‘events’

0
0
0
6
10
20
30
40
50

foo()
setInterval(bar, 10)
setTimeout(nerf, 20)
Button clicked
Interval fires
Interval & Timer fire
Interval fires
Interval fires
Interval fires

bar()

bar()

click
bar() nerf() bar()
handler
20

ms

30

40

bar()

bar()
50
Conclusions
•

If code is already executing, events and timers are
queued

•

Timers may not execute exactly when you were
expecting

•

Intervals may not fire as often as you were expecting

•

User interaction is queued as well, which the user
interprets as the UI being unresponsive.
setTimeout vs setInterval
setTimeout ( function nerf() {
	 …..
	 setTimeout ( nerf, 10);
}, 10);
-VSsetInterval ( function() {
	 …..
}, 10);
Underscore - Defer
_.defer(function, [*arguments])
Defers invoking the function until the current call stack has cleared,
similar to using setTimeout with a delay of 0. Useful for performing
expensive computations or HTML rendering in chunks without blocking
the UI thread from updating. If you pass the optional arguments, they
will be forwarded on to the function when it is invoked.
!

_.defer ( function() { alert(‘deferred’); });
!

// Returns from the function before the alert runs.
Live demo

Defer FTW!
https://github.com/RonaldTreur/lp.DeferTests

The above link contains the live demo test cases
Conclusions
•

Try to keep the User experience as responsive as
possible. Use _.defer!

•

Always show loading-indicators when you can’t.

•

Limit the amount of actions everywhere in your app. For
example: Widgitize your button and/or use _.throttle.
Underscore - Throttle
_.throttle(function, wait, [options])
Creates and returns a new, throttled version of the
passed function, that, when invoked repeatedly,
will only actually call the original function at most
once per every wait milliseconds. Useful for ratelimiting events that occur faster than you can keep
up with.
var throttled = _.throttle ( updatePosition, 100);
$(window).scroll(throttled);
The End

Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Baruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion WorkshopBaruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion Workshop
Brian Sam-Bodden
 

Was ist angesagt? (20)

Setting UIAutomation free with Appium
Setting UIAutomation free with AppiumSetting UIAutomation free with Appium
Setting UIAutomation free with Appium
 
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
 
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerE2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
 
Hacking iOS Simulator: writing your own plugins for Simulator
Hacking iOS Simulator: writing your own plugins for SimulatorHacking iOS Simulator: writing your own plugins for Simulator
Hacking iOS Simulator: writing your own plugins for Simulator
 
React Native: The Development Flow
React Native: The Development FlowReact Native: The Development Flow
React Native: The Development Flow
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
JAVA INTRODUCTION
JAVA INTRODUCTIONJAVA INTRODUCTION
JAVA INTRODUCTION
 
Reactive Streams and RxJava2
Reactive Streams and RxJava2Reactive Streams and RxJava2
Reactive Streams and RxJava2
 
C# Security Testing and Debugging
C# Security Testing and DebuggingC# Security Testing and Debugging
C# Security Testing and Debugging
 
iOS Parallel Automation: run faster than fast — Viktar Karanevich — SeleniumC...
iOS Parallel Automation: run faster than fast — Viktar Karanevich — SeleniumC...iOS Parallel Automation: run faster than fast — Viktar Karanevich — SeleniumC...
iOS Parallel Automation: run faster than fast — Viktar Karanevich — SeleniumC...
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
 
Seven Versions of One Web Application
Seven Versions of One Web ApplicationSeven Versions of One Web Application
Seven Versions of One Web Application
 
iOS Parallel Automation - Viktar Karanevich - Mobile Test Automation Meetup (...
iOS Parallel Automation - Viktar Karanevich - Mobile Test Automation Meetup (...iOS Parallel Automation - Viktar Karanevich - Mobile Test Automation Meetup (...
iOS Parallel Automation - Viktar Karanevich - Mobile Test Automation Meetup (...
 
Scala for Test Automation
Scala for Test AutomationScala for Test Automation
Scala for Test Automation
 
Apache ANT vs Apache Maven
Apache ANT vs Apache MavenApache ANT vs Apache Maven
Apache ANT vs Apache Maven
 
Baruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion WorkshopBaruco 2014 - Rubymotion Workshop
Baruco 2014 - Rubymotion Workshop
 
JavaOne - The JavaFX Community and Ecosystem
JavaOne - The JavaFX Community and EcosystemJavaOne - The JavaFX Community and Ecosystem
JavaOne - The JavaFX Community and Ecosystem
 
Introduction to Groovy Monkey
Introduction to Groovy MonkeyIntroduction to Groovy Monkey
Introduction to Groovy Monkey
 
Workshop: Functional testing made easy with PHPUnit & Selenium (phpCE Poland,...
Workshop: Functional testing made easy with PHPUnit & Selenium (phpCE Poland,...Workshop: Functional testing made easy with PHPUnit & Selenium (phpCE Poland,...
Workshop: Functional testing made easy with PHPUnit & Selenium (phpCE Poland,...
 
Introduction to Apache Ant
Introduction to Apache AntIntroduction to Apache Ant
Introduction to Apache Ant
 

Andere mochten auch

Titanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performanceTitanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performance
omorandi
 

Andere mochten auch (6)

Javascript로 네이티브 iOS, Android앱 만들기 - Titanium
Javascript로 네이티브 iOS, Android앱 만들기 - TitaniumJavascript로 네이티브 iOS, Android앱 만들기 - Titanium
Javascript로 네이티브 iOS, Android앱 만들기 - Titanium
 
Titanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performanceTitanium Mobile: flexibility vs. performance
Titanium Mobile: flexibility vs. performance
 
10 Golden Rules For Outstanding Titanium Apps
 10 Golden Rules For Outstanding Titanium Apps 10 Golden Rules For Outstanding Titanium Apps
10 Golden Rules For Outstanding Titanium Apps
 
[Jscamp] Titanium - Javascript를 이용한 크로스 플랫폼 앱 개발
[Jscamp] Titanium - Javascript를 이용한 크로스 플랫폼 앱 개발[Jscamp] Titanium - Javascript를 이용한 크로스 플랫폼 앱 개발
[Jscamp] Titanium - Javascript를 이용한 크로스 플랫폼 앱 개발
 
Titanium 소개 - 당신이 알고 있는 타이타늄 rev.201310
Titanium 소개 - 당신이 알고 있는 타이타늄 rev.201310Titanium 소개 - 당신이 알고 있는 타이타늄 rev.201310
Titanium 소개 - 당신이 알고 있는 타이타늄 rev.201310
 
LAP2 iOS and Android Development environment setup
LAP2 iOS and Android Development environment setupLAP2 iOS and Android Development environment setup
LAP2 iOS and Android Development environment setup
 

Ähnlich wie Titanium - Making the most of your single thread

High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas
 

Ähnlich wie Titanium - Making the most of your single thread (20)

Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
Java multi thread programming on cmp system
Java multi thread programming on cmp systemJava multi thread programming on cmp system
Java multi thread programming on cmp system
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
 
Realtime selenium interview questions
Realtime selenium interview questionsRealtime selenium interview questions
Realtime selenium interview questions
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
 
Debugging Complex Systems - Erlang Factory SF 2015
Debugging Complex Systems - Erlang Factory SF 2015Debugging Complex Systems - Erlang Factory SF 2015
Debugging Complex Systems - Erlang Factory SF 2015
 
Stateful patterns in Azure Functions
Stateful patterns in Azure FunctionsStateful patterns in Azure Functions
Stateful patterns in Azure Functions
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
Develop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverlessDevelop in ludicrous mode with azure serverless
Develop in ludicrous mode with azure serverless
 
Devignition 2011
Devignition 2011Devignition 2011
Devignition 2011
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
Troubleshooting: The Two Laws - IXIASOFT User Conference 2016
 
Conf orm - explain
Conf orm - explainConf orm - explain
Conf orm - explain
 
High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
 
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with DebuggingPART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
PART-3 : Mastering RTOS FreeRTOS and STM32Fx with Debugging
 
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attacDefcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
Defcon 22-paul-mcmillan-attacking-the-iot-using-timing-attac
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Beyond the RTOS: A Better Way to Design Real-Time Embedded Software
Beyond the RTOS: A Better Way to Design Real-Time Embedded SoftwareBeyond the RTOS: A Better Way to Design Real-Time Embedded Software
Beyond the RTOS: A Better Way to Design Real-Time Embedded Software
 
When Web Services Go Bad
When Web Services Go BadWhen Web Services Go Bad
When Web Services Go Bad
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Krashi Coaching
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Titanium - Making the most of your single thread

  • 1. Making the most of your single thread Titanium - Fundamentals
  • 2. Congrats! ! Your app is in the hands of the public! Your users click on buttons, open windows, and at some point someone touches a button that results in…
  • 3. Absolutely Nothing. He tries touching it three times, before deciding, after a mere few seconds, that your app has crashed. ! He kills your app.
  • 4. Had he waited for ‘but’ 5 seconds.. .. he would have noticed three windows opening in rapid succession. Three identical windows, as he would observe when using the ‘back’-button.
  • 5. What did you do wrong? • There’s no loading indicator showing • There is no mechanic in place to prevent additional windows from opening
  • 6. What did you do wrong? • There’s no loading indicator showing • There is no mechanic in place to prevent additional windows from opening • But more important: You blocked the UI far too long! You did not make the best use of your single thread!
  • 7. Ronald Treur Co-founder Snowciety ! Freelance developer ! 2.5 yrs Titanium experience ! @ronaldtreur ronald@funcracker.net
  • 8. Making the Most of Your Single Thread • Threads & Threading • How it works in Native & Titanium • Javascript call stack example • Underscore - Defer
  • 9. Thread The smallest subset of a process that could be independently handled by the OS. or The smallest piece of code, that could be executed independently from the rest of the code.
  • 11. Threading • Multi-threaded: 
 - Threads (can) run in parallel, meaning:
 - Multiple pieces of code can execute at the same time. #1 #2 ! #3 #4 ! • #1 Single-threaded:
 - Threads can only run serially, meaning:
 - Only one piece of code can execute at a time. #2 #3
  • 14. How your app works JS Thread #1
  • 15. Thread Safe Javascript is by definition NOT thread safe. • If multiple threads would be able to access and change the same object/variable, a race condition might occur. • aka: the outcome of a piece of code would be unpredictable.
  • 16. Single Threaded Javascript is by definition NOT thread safe. Thus it is, by nature, single threaded. • Timers are not part of Javascript, they are part of the JS engine (Rhino, V8, JavaScriptCore) • Timers allow for asynchronous delays, but code execution remains single threaded. • When a timer expires, or an event fires, the resulting execution is queued.
  • 18. Call Stack ms ‘events’ 0 0 0 foo() setInterval(bar, 10) setTimeout(nerf, 20) nerf() foo() bar() bar() bar() bar() bar() 30 40 50 foo() 0 10 20 ms
  • 19. Call Stack [click] foo() ‘events’ 0 0 0 6 foo() setInterval(bar, 10) setTimeout(nerf, 20) Button clicked nerf() bar() foo() 0 ms 10 bar() bar() bar() bar() 30 40 50 click handler 20 ms
  • 20. Call Stack ms In Titanium the queue is FIFO (first in, first out). [click] foo() 0 0 0 6 10 foo() setInterval(bar, 10) setTimeout(nerf, 20) Button clicked Interval fires nerf() bar() foo() 0 ‘events’ 10 bar() bar() bar() bar() 40 50 click bar() handler 20 ms 30
  • 21. Call Stack [click] foo() ‘events’ 0 0 0 6 10 20 foo() setInterval(bar, 10) setTimeout(nerf, 20) Button clicked Interval fires Interval & Timer fire nerf() bar() foo() 0 ms 10 bar() bar() bar() bar() click bar() nerf() handler 20 ms 30 40 50
  • 22. Call Stack ms The interval at 20ms is ignored, an execution is already scheduled. [click] foo() 0 0 0 6 10 20 foo() setInterval(bar, 10) setTimeout(nerf, 20) Button clicked Interval fires Interval & Timer fire nerf() bar() foo() 0 ‘events’ 10 bar() bar() bar() bar() click bar() nerf() handler 20 ms 30 40 50
  • 23. Call Stack ms The interval at 30ms is queued, since no execution is scheduled. [click] foo() 0 0 0 6 10 20 30 foo() setInterval(bar, 10) setTimeout(nerf, 20) Button clicked Interval fires Interval & Timer fire Interval fires nerf() bar() foo() 0 ‘events’ 10 bar() bar() bar() bar() click bar() nerf() bar() handler 20 ms 30 40 50
  • 24. Call Stack ms ‘events’ nerf() 0 0 0 6 10 20 30 40 foo() setInterval(bar, 10) setTimeout(nerf, 20) Button clicked Interval fires Interval & Timer fire Interval fires Interval fires bar() bar() Interval at 40ms is ignored. [click] foo() bar() foo() 0 10 bar() bar() click bar() nerf() bar() handler 20 ms 30 40 50
  • 25. Call Stack ms Interval at 50ms is the first to execute at the correct time (though 2 executions were dropped). [click] foo() nerf() bar() foo() 0 10 bar() ‘events’ 0 0 0 6 10 20 30 40 50 foo() setInterval(bar, 10) setTimeout(nerf, 20) Button clicked Interval fires Interval & Timer fire Interval fires Interval fires Interval fires bar() bar() click bar() nerf() bar() handler 20 ms 30 40 bar() bar() 50
  • 26. Conclusions • If code is already executing, events and timers are queued • Timers may not execute exactly when you were expecting • Intervals may not fire as often as you were expecting • User interaction is queued as well, which the user interprets as the UI being unresponsive.
  • 27. setTimeout vs setInterval setTimeout ( function nerf() { ….. setTimeout ( nerf, 10); }, 10); -VSsetInterval ( function() { ….. }, 10);
  • 28. Underscore - Defer _.defer(function, [*arguments]) Defers invoking the function until the current call stack has cleared, similar to using setTimeout with a delay of 0. Useful for performing expensive computations or HTML rendering in chunks without blocking the UI thread from updating. If you pass the optional arguments, they will be forwarded on to the function when it is invoked. ! _.defer ( function() { alert(‘deferred’); }); ! // Returns from the function before the alert runs.
  • 31. Conclusions • Try to keep the User experience as responsive as possible. Use _.defer! • Always show loading-indicators when you can’t. • Limit the amount of actions everywhere in your app. For example: Widgitize your button and/or use _.throttle.
  • 32. Underscore - Throttle _.throttle(function, wait, [options]) Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for ratelimiting events that occur faster than you can keep up with. var throttled = _.throttle ( updatePosition, 100); $(window).scroll(throttled);