Gmail for Mobile HTML5 Series: Using Timers Effectively
Gmail for Mobile HTML5 Series: Using Timers Effectively
The dashed blue line represents the requested timer interval, 200 ms. Notice that the median was almost 50% higher than requested, at 276 ms; the time between ticks varied from 98 ms to almost 4 seconds, with an average delay of 493 ms.
This highlights the fact that the interval at which your timer actually fires may differ greatly from the requested delay. In fact, the time between ticks is typically highly variable. It will fluctuate based on what else is happening in your application and on the device. Don't rely on your timer being precise!
Here's what we learned. With low-frequency timers — timers with a delay of one second or more — we could create many timers without significantly degrading performance on either device. Even with 100 timers scheduled, our app was not noticeably less responsive. With high-frequency timers, however, the story was exactly the opposite. A few timers firing every 100-200 ms was sufficient to make our UI feel sluggish.
This led us to take a mixed approach with the timers we use in our application. For timers that have a reasonably long delay, we just freely create new timers wherever they are needed. However, for timers that need to execute many times each second, we consolidate all of the work into a single global high-frequency timer.
A global high-frequency timer strikes a balance between needing several different functions to execute frequently and application performance. The idea is simple: create a single timer in a central class that calls as many functions as required. Ours looks something like this:
var highFrequencyTimerId_ = window.setInterval(globalTimerCallback, 100);
globalTimerCallback = function() {
navigationManager.checkHash();
spinnerManager.spin();
detectWakeFromSleep_();
};
沒有留言:
張貼留言