8 Replies Latest reply on Dec 5, 2016 12:05 PM by kerrishotts

    How can I deal with async execution in phonegap?

    faustot4544220 Level 1

      How does phonegap deal with multi-threading? If it runs in a single thread how can run things async, or parallel, or in background?

        • 1. Re: How can I deal with async execution in phonegap?
          kerrishotts Adobe Employee

          There are two sides to this answer -- the native side and the JavaScript side.




          On the native side, PG has access to the OS's native multi-threaded capabilities. This doesn't necessarily mean that plugins and such will use that functionality, but it's there if a plugin or other native code that needs that feature, it's a available.




          JavaScript is mostly single-threaded. Single-threading does not prevent asynchronous code, although it does prevent parallelism. I say "mostly" because web workers are a thing now, and each worker runs on its own thread, which does mean you can have some parallelism.


          To understand how JavaScript accomplishes asynchrony while still being single-threaded requires that you understand the JavaScript event loop. The event loop is directed by the web view, and (in pseudo-code) might look something like this:


          while (event = waitForEvent) {


             processOtherStuff(); // like style updates, DOM updates, rendering, etc.



          JavaScript is executed to completion, so it's possible to block the main thread if you're executing a long-running computation. JS code can schedule code to execute later, however, by using timers and intervals. This means you can break up a long-running computation over an interval where only a small portion of the computation is completed each interval.


          JavaScript is also event-driven. Events aren't just touches or clicks, but other things as well (such as I/O completion). Cordova uses this as well to handle the native/web bridge, meaning that when a plugin finishes some task, it schedules some JavaScript code (your callback) on the next run through the event loop.


          The long & short of all this is that if you want your code to avoid blocking the main thread AND you want your app to maintain 60fps, your code needs to complete within 16.67ms.


          You should read up more on the JavaScript Event Loop: Concurrency model and Event Loop - JavaScript | MDN


          Hope that helps.

          1 person found this helpful
          • 2. Re: How can I deal with async execution in phonegap?
            faustot4544220 Level 1

            I got it. well, you shared a lot of useful and worth information. thanks.


            So am I able to build an application that works and looks so natively and smoothly like snapchat, facebook messenger, youtube?

            • 3. Re: How can I deal with async execution in phonegap?
              kerrishotts Adobe Employee

              Please be more specific as to the kind of application you're building. The apps you've mentioned are so varied and have so many features embedded within them, it's hard to know how to answer your question. There are some features that should be delegated to native code -- for example, I wouldn't build the next Minecraft using HTML and JavaScript.


              Without more info: it's possible to create apps that achieve 60fps and feel (mostly) native.You can do this the hard way (writing all the code yourself) or using frameworks that optimize for fluidity (Ionic, Framework7, etc.). Keep in mind that a framework won't guarantee you anything -- it's still possible to write bad code that brings a framework to its knees.


              Regardless of which (or any) framework you use, you should have an excellent understanding of JavaScript, how it works in the browser context, and how the browser manages the DOM. You also need access to profilers (both Chrome and Safari have these tools) so that you test that your app is rendering quickly. Without these things there's very little chance you'll write an app that is performant. (Essentially you should be good at writing silky-smooth web apps that run in a mobile web browser. If you can do that, you can do the same with a PhoneGap app.)


              Also: A lot of devices running Android feature single-core performance significantly worse than Apple devices. This can make it very difficult to achieve 60fps UIs on those devices. (In fact, I have an Android tablet that can't even manage to render NATIVE apps at 60fps without dropping frames. Hybrid apps are doomed on that device.) I suggest making sure your app can degrade gracefully (limit/disable animations, limit/disable expensive CSS rules, etc.)


              You might want to review the information on jank (<60fps and frame drops) here: Jank Free: Let's Make the Web Silky Smooth!

              2 people found this helpful
              • 4. Re: How can I deal with async execution in phonegap?
                faustot4544220 Level 1

                We are going almost to jquery + bootstrap and keep things simple. We've worked a lot on ux/ui to get things as simple as smoothly. The app does:

                • send/receive data such as photo/video in realtime (one-to-one and one-to-many).
                • fast search/suggestion.
                • it'll be a bit clutter in the future but we are going to solve it as a ux problem. we consider to go natively if it really is an issue.
                • push notifications.
                • realtime updates.
                • no endless scroll


                I think it's not a really complex app but there is a lot of things happening at the same time.

                • 5. Re: How can I deal with async execution in phonegap?
                  kerrishotts Adobe Employee

                  How your app handles the DOM and how quickly it can re-render itself in the DOM will be the critical factor here. I'm assuming by video/photos you just mean files, not real-time video streaming (you'd have to verify support on targeted platforms).


                  Above all, your code AND all the resulting DOM layout, compositing and painting must finish with 16.67ms in order for your user to see a 60fps app. This will be easier on iOS compared to Android just because of iOS' faster single-threaded performance. Even so, it's easy to bring any device to its knees if you don't treat the DOM carefully. Keep the # of DOM elements low, avoid expensive CSS styles (or have a way to disable them when on slow devices), and avoid thrashing the DOM. Optimize images and video for the device the user has so that the browser doesn't have to do a lot of scaling and bandwidth can be reduced (especially important on cellular networks).


                  There's nothing inherently wrong with choosing jQuery, although it is incredibly easy to write jQuery code that is horribly slow. Be sure to cache jQuery objects (selectors and conversion of DOM objects to jQuery objects can be slow). (I'd give the same advice if you weren't using jQuery, but it'd be to cache DOM elements instead.) Batch reads and writes to the DOM to minimize thrashing.


                  Hope that helps!

                  1 person found this helpful
                  • 6. Re: How can I deal with async execution in phonegap?
                    faustot4544220 Level 1

                    Well. We probably we will have something with realtime stuff. I searched around and it can be solved maybe with WebRTC. I don't know how it'll perform.


                    Since facebook, linkedin and others platforms built their first apps with hybrid solution, I can assume that's a way to go.


                    I'm only worried to choose it and find pitfals.


                    I checked your first answer as corrent but I'd liked to mark all of them. That's all useful.

                    • 7. Re: How can I deal with async execution in phonegap?
                      faustot4544220 Level 1

                      Could I build a phonegap plugin to run things parallel? Or a plugin to help the javascript be faster and responive?


                      I mean by using plugin I think that's possible delegate things to OS.

                      • 8. Re: How can I deal with async execution in phonegap?
                        kerrishotts Adobe Employee

                        Yes, you can build whatever plugins you like. Keep in mind, however, that plugins that work with the OS will be native code, and so you'll have to be sure to write native code for each supported platform.


                        You'll not be able to do much with regard to JS performance itself other than:

                        • Use the Crosswalk plugin for Android (not necessarily faster, but consistent across all supported targets)
                        • Use WKWebView for iOS (not a drop-in, has its own caveats, but uses iOS's JIT engine -- up to 3x faster than UIWebView)
                        • For multiple threads, use web workers where possible and supported
                        • Break your tasks up into smaller pieces that can fit within 16.67ms
                        • As a last resort, use a plugin to take over the task entirely. Again, though, this would be NATIVE code, and so needs to be written for every platform you target.
                        1 person found this helpful