Using a timeout with a promise (HTML)

[This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation]

In some circumstances, you might want to have an asynchronous operation complete within a certain time span or else get canceled. You can use WinJS.Promise.timeout to accomplish this.

In this example, WinJS.xhr is used to download a web page. If the download isn't complete within 1500 milliseconds, the download is canceled. This example is designed to write the output to the JavaScript Console in Microsoft Visual Studio.

Wrap the WinJS.xhr function in a call to WinJS.Promise.timeout. You add a completed function to report when the download is complete, and an error function to report on the error.

WinJS.Utilities.startLog();

WinJS.Promise.timeout(1500, WinJS.xhr({ url: "https://www.microsoft.com" })
    .then(function complete(result) {
        WinJS.log && WinJS.log("Downloaded the page");
    },
    function error(error){
        // The error thrown when xhr is canceled has a message property, not a statusText property.
        if (error.statusText) {
            WinJS.log && WinJS.log("Got error: " + error.statusText);
        }
        else {
            WinJS.log && WinJS.log("Got error: " + error.message);
        }
    }));

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.

When you run this code, the web request should complete without errors, and the console should output the success of the operation. To see what happens when the request is canceled, shorten the timeout period to 200 milliseconds:

WinJS.Utilities.startLog();

WinJS.Promise.timeout(200, WinJS.xhr({ url: "https://www.microsoft.com" })
    .then(function complete(result) {
        WinJS.log && WinJS.log("Downloaded the page");
    },
    function error(error){
        // The error thrown when xhr is canceled has a message property, not a statusText property.
        if (error.statusText) {
            WinJS.log && WinJS.log("Got error: " + error.statusText);
        }
        else {
            WinJS.log && WinJS.log("Got error: " + error.message);
        }
    }));

In this case the web request should be canceled. The console should read "Got error: Canceled".