Nanego
Nanego

Reputation: 1905

How to retrieve data only if user stay more than one second on the page

In an AngularJS app, users can navigate through several pages. Each time a page is displayed, the controller fetches the server to retrieve some data.

I would like to wait 1 second before launching the request, so we do not load data if the user has quickly left the page for another view.

I tried to use $timeout but the query is executed even if an other view and an other controller have been loaded.

app.controller('showController', function($scope, $routeParams, $timeout){
  $timeout(function(){
    Service.getDataDetails(id).then(function (result) {
      $scope.data = result;
    });
  },1000);
});

I also tried to cancel the query. The query is well canceled in the navigator, but the server still execute it.

Upvotes: 0

Views: 73

Answers (5)

Florian Gl
Florian Gl

Reputation: 6014

Cancel your $timeout in the destructor of your controller:

$scope.$on("$destroy", function handler() {
    $timeout.cancel(promise);
});

It is called when the controller is not used anymore.


Patrick Evens reminded me of telling you where the promise variable comes from:

var promise = $timeout(function(){
    Service.getDataDetails(id).then(function (result) {
        $scope.data = result;
    });
},1000);

Upvotes: 2

Michael
Michael

Reputation: 337

Get the $timeout id by assigning it to a variable like so: var timeoutID = $timeout(....

Right before the $timeout block, within the same scope, clear the timeout with $timeout.cancel( timeoutID ). This ensures that the code within the $timeout block will not be executed if a user navigates to a new page within the the 1000ms.

Upvotes: 0

Edminsson
Edminsson

Reputation: 2506

Cancelling the timeout should work if it haven't fired the call to the server.

var timer = $timeout(function(){
    Service.getDataDetails(id).then(function (result) {
      $scope.data = result;
    });
},1000);

and cancelling the timeout like this:

$timeout.cancel(timer);

Upvotes: 0

vikash
vikash

Reputation: 36

when you make a request, control goes to server and then in response only you get a view. So in document ready you can have timeout, this will not prevent server call. To prevent server call you need to write code in controller to wait for 1second before sending response. I hope this might clear.

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42736

The $timeout service has a cancel method to cancel a timeout

var promise = $timeout(function(){
  Service.getDataDetails(id).then(function (result) {
    $scope.data = result;
  });
},1000);
//...
//somewhere else
$timeout.cancel(promise);

The cancel method will cause the promise to be rejected instead of resolved.

Upvotes: 2

Related Questions