When you use XMLHttpRequest, you can set time-out values directly, but you cannot do this when you use WinJS.xhr. However, there is a way to set time-outs on WinJS.Promise objects. By calling WinJS.Promise.timeout, you ensure that the request is canceled if it has not completed within the specified time.
In the code from the XhrExample project that is created in Quickstart: Downloading a file with WinJS.xhr, wrap the WinJS.xhr function in a call to WinJS.Promise.timeout.
Note that when you use WinJS.Promise.timeout in this way, you need to use then, which returns a Promise when there is an error, rather than done, which does not.
var xhrDiv = document.getElementById("xhrReport"); WinJS.Promise.timeout(1500, WinJS.xhr({ url: "http://www.microsoft.com" }) .then(function complete(result) { xhrDiv.innerText = "Downloaded the page"; xhrDiv.style.backgroundColor = "#00FF00"; }, function error(error){ // The error thrown when xhr is canceled has a message property, not a statusText property. if (error.statusText) xhrDiv.innerHTML = "Got error: " + error.statusText; else xhrDiv.innerHTML = "Got error: " + error.message; xhrDiv.style.color = "#000000"; xhrDiv.style.backgroundColor = "#FF0000"; }, function progress(result) { xhrDiv.innerText = "Ready state is " + result.readyState; xhrDiv.style.color = "#000000"; xhrDiv.style.backgroundColor = "#0000FF"; }));
When you run this code, the web request should complete without errors, and you should see the DIV turn green. To see what happens when the request is canceled, shorten the timeout period to 200 milliseconds:
var xhrDiv = document.getElementById("xhrReport"); WinJS.Promise.timeout(200, WinJS.xhr({ url: "http://www.microsoft.com" }) .then(function complete(result) { xhrDiv.innerText = "Downloaded the page"; xhrDiv.style.backgroundColor = "#00FF00"; }, function error(error){ // The error thrown when xhr is canceled has a message property, not a statusText property. if (error.statusText) xhrDiv.innerHTML = "Got error: " + error.statusText; else xhrDiv.innerHTML = "Got error: " + error.message; xhrDiv.style.color = "#000000"; xhrDiv.style.backgroundColor = "#FF0000"; }));
In this case the web request should be canceled. The DIV should turn red, and you should see the message "Got error: Canceled".
Related topics
Build date: 10/26/2012