In this, the third, post in my series “Windows 8: What I’ve learned,” I’ll share how the behavior of script loading and unloading in some Windows 8 Metro app templates require a different approach to using setTimeout for timers.
Background
I recently had the opportunity to spend some more quality time with the Visual Studio 2012 release candidate, building a Windows 8 app for some of my teammates who focus on Windows Azure, Brian Hitney, Peter Laudati, and Jim O’Neil. You can see a screenshot of the app to the left.
One of the really cool things that these guys have built on top of Windows Azure is the Rock Paper Azure Challenge, an contest to see who can code the most effective online bot to play the game Rock, Paper, Scissors in the cloud. Cool prizes are available, from Best Buy gift cards, to Windows Phones to XBOXes and Kinects.
For TechEd North America this week, they came up with a very special contest, called Beat The Gu. The idea is simple…Scott Guthrie (whom most of you probably know now runs the Azure team), has a RockPaperAzure bot, and TechEd attendees could compete to see who could beat his bot (with a top prize of a 60″ LCD TV).
One of the features that the Rock Paper Azure Challenge provides is a set of leaderboards for all of the various contests that are currently running, with the data accessible via the OData protocol. This makes it super-simple to grab the data in a Windows 8 Metro style app as either XML (ATOM-Pub format) or JSON. I chose to build the app using HTML and JavaScript, so JSON format was perfect.
I’ll be sharing more details on the app and what went into it in a future post, but for now I want to focus on one of the things that bit me during the development process, namely using setTimeout to create a timer.
What I Learned
For the Rock Paper Azure Leaderboard app, I used the Navigation app template, which consists of a default.html page containing a div that becomes an instance of the PageControlNavigator class, which is defined in a script file called navigation.js. Basically this control provides an easy way to dynamically load fragments of markup, CSS and script referred to as Page controls at runtime. And the way that script resources are loaded and unloaded is a little different when using this template, as we’ll see in a bit. You can read more about how single-page navigation works here.
One of the most important features was for the leaderboard information on the home page to be refreshed periodically, since the contest takes place in rounds and after each round, the position of the players will typically change. Since I was using HTML and JavaScript to build the app, the natural way of doing this was to use JavaScript’s setTimeout function to periodically refresh the data.
In earlier versions of the app, I had code in the home page’s ready function that would call a function in my data.js file (modeled after the pattern in the Grid app template) to retrieve a WinJS.Binding.List with the leaderboard data, then bind that data to a ListView on the page. Once all that was done, I would call setTimeout, passing it the name of the function to refresh the data, along with the timeout duration, something like this:
1: ready: function (element, options) {
2: var promise = Data.init();
3: promise.done(
4: function (leaderboardList) {
5: leaderListView.winControl.itemDataSource = leaderboardList.dataSource;
6: setTimeout(dataUpdateLoop, 30000);
7: }
8: );
9: }
Essentially, the code above will call a function named dataUpdateLoop after 30 seconds. This works great…as long as you stay on the home page.
Although Windows 8 apps written in HTML and JavaScript use standards-based technologies, there are some subtle differences in how the JavaScript and CSS files are loaded (and unloaded, importantly) when using the Navigation app template. With a web site, when you switch to a different page, the DOM is unloaded, and any scripts that were running are no longer in scope. The new page is then loaded, along with any scripts it references.
In an app based on the Navigation template, script loading is a little different. When I run the app, all of the scripts and such required to display the homepage are loaded, as shown in the Solution Explorer screen capture to the left. The base.js and ui.js files are part of the WinJS library, and will always be loaded in a Metro style app (they’re referenced in default.html). default.js and navigator.js are loaded by default.html, and provide support functionality for the entire app, since default.html acts as a parent container for the whole app. settingsUtil.js and searchResults.js are also loaded by default.html, and support the Settings pane and Search contract, respectively.
The remaining JavaScript files, data.js, home.js, and converters.js, are loaded by home.html, which is a Page control that is loaded automatically when the app starts up. Now let’s take a look at what happens when we go to a different part of the application, for example, we can visit the player details page by tapping or clicking on one of the player tiles on the leaderboard:
When the details page loads, we see the screen to the right, which shows us the details for the selected player, including their current place, number of wins and losses and ties, total points, and the date and time of their last match. But of greater interest is what happens with our scripts. If we take another look at the Solution Explorer, we’ll see that another script has been loaded, playerDetails.js, as shown below:
In addition to the new JavaScript file being loaded, notice what didn’t happen…none of the previously loaded scripts were unloaded. BUT…the controls on the homepage (most critically the ListView control containing the leaderboard info) are no longer instantiated. The impact of this, as I discovered in testing the application, is that the timer I set in the code above continues executing, but because leaderListView is no longer instantiated, the dataUpdateLoop function will throw an exception.
Suffice it to say, this was not an acceptable result. I still needed to update the leaderboard on a regular basis, but having the app throw exceptions or crash if I tried to look at the details or use other functionality in the app was not OK.
The Solution
I’m sure there are probably any number of ways to work around a problem like this, but here’s what I came up with (I welcome suggestions for a more elegant or robust solution in the comments). The key is to clear the timer when you move to a different page, and restart the timer when you come back to the home page. Conveniently, JavaScript includes a function for just this purpose, called clearTimeout (there’s a corresponding version for setInterval as well if you’re doing timers that way). But you need to do a little more work in order to use it. clearTimeout requires you to provide it with the ID of the timer you want to clear, which conveniently is a return value of the setTimeout function when called (in my code above, I was simply ignoring this value).
To implement this, I refactored my code as follows:
1: ready: function (element, options) {
2: var promise = Data.init();
3: promise.done(
4: function (leaderboardList) {
5: leaderListView.winControl.itemDataSource = leaderboardList.dataSource;
6: if (appSettings.refreshData()) {
7: appdata.current.localSettings.values["currentTimeoutId"] =
8: setTimeout(dataUpdateLoop, appSettings.refreshDataInterval());
9: }
10: }
11: );
12: }
In the bold section of the code above, I’m capturing the ID of the timer that I’m creating with setTimeout, and storing it as value named “currentTimeoutId” in my local settings. That allows me to access the ID later if I need to clear the timer. I’ve also modified the code to include a check of another setting, refreshData, which is defined in settingsUtil.js, and is a boolean value indicating whether or not to perform the refresh. I’ve also moved the refresh interval into a setting which is likewise exposed by settingsUtil.js. To cancel the timer when navigating to another page, I simply add the following code to the function that’s mapped to the ListView’s oniteminvoked event:
1: function itemInvoked(args) {
2: args.detail.itemPromise.done(
3: function (item) {
4: if (appdata.current.localSettings.values["currentTimeoutId"]) {
5: clearTimeout(appdata.current.localSettings.values["currentTimeoutId"]);
6: }
7: WinJS.Navigation.navigate("/pages/details/playerDetails.html", item.data);
8: }
9: );
10: }
In the bold section of the code above, I’m testing whether I’ve captured an ID from a call to setTimeout, and if so, I’m calling clearTimeout and passing in the relevant timer ID. That’s all there is to it!
Summary
When using JavaScript to write an application, whether for the web, or for a Windows 8 app, you need to be careful to understand the scope in which your code is executing, as well as when that code is loaded and unloaded. The Windows 8 Metro app development environment helps you by including best practices, such as wrapping your page code inside a self-executing anonymous function, to help you avoid problems with variable name collisions, etc. The Navigation template is a great place to start because it provides some key infrastructure (including a consistent back button users can use to go back to the previous page) to help you help your users find their way around your app. But you need to keep in mind that script loading in a Metro style app behaves somewhat differently when using the Navigation template to implement single-page navigation.
Note that this tip also applies to the Grid App and Split App templates, since they use the same single-page navigation pattern using navigator.js.
I hope you found this tip useful…if so, please share with your friends and colleagues!
Comments
Comment by Johnkingsley06 on 2012-09-20 09:25:00 +0000
Thanks for posting.
One query: Mine is a HTML5/ WinJS/ C# Windows 8 App.
JavaScript Functions will call a model in C# components where all service call will be done.
When I run my app in Windows 8 Tablet, [Not in local machine,Simulator], The app is crashing so many times.
We have clear-timeout, clear-interval as you mentioned above.
Still App crash repeatedly happening. Can you tell any suggestions for that?
Any best practices in WinJS?
Comment by devhammer on 2012-09-22 12:57:00 +0000
Without seeing the error messages, or knowing more about your app, it’s impossible to say what might be causing the issue. Check out this article, which may help with debugging:
http://msdn.microsoft.com/en-us/library/windows/apps/hh441474.aspx
Comment by Gianca on 2013-05-05 08:39:00 +0000
Great post, I have to study it. I’ve just released a Guitar Ear Training App, http://www.fachords.com/guitar-ear-training/ it uses javascript timer and I have some problems on Windows 8. I will start to investigate from this post. Thank you