简体   繁体   中英

Find duration of a REST call in Angular.js

I want to find out the time taken by a REST service to send back the promise object. If a REST service takes more than lets say x seconds, I need to show user a spinner and once the promise object is obtained the normal flow should proceed.

Any ideas?

Thanks

Recording the time of the request seems unnecessary.

Why not just always setup a timeout that will trigger the spinner after x seconds. In the success callback of the promise you can just destroy the timeout object preventing it from triggering the spinner if it's before x seconds. Then remove the spinner if it exists.

var duration = 1000 * 1; //1 sec
var timeout = setTimeout(releaseTheSpinner, duration);
var releaseTheSpinner = function() {
  //Make spinner
}
Something.update(data).
success(function {
  clearTimeout(timeout);
  //kill spinner
})

Using setTimeout should suffice. For example:

$scope.useHttp = function() {
    $http.get('path/to/stuff')
        .success(function(data) {
            hideSpinner();
            //do stuff with data
        });
    setTimeout(showSpinner,1000); //will show the spinner after a second (1000 milliseconds).
};

Have a look at the ngProgress directive or the angular loading bar directive , which place a progress at the top of the page. This creates a general, uniform method of displaying progress. Even if the service responds quickly (which is when you don't want to show a progress), the bar moves very quickly. This isn't a direct answer to your question, but a suggested alternative to added complexity around timing and showing a spinner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM