raddevon
raddevon

Reputation: 3340

Cancel new request instead of currently loading request when refreshing an image with Angular's $timeout

I'm using Angular's timeout to refresh the contents of an image at a user-specified interval. When that interval is too low for the image to load (e.g. 1 second), each subsequent request cancels the previous one causing the image to never refresh.

Chrome Dev Tools network tab showing canceled requests

Instead of this behavior, I would like for the current request to complete and for subsequent requests to be canceled until that one is completed when requests collide. How can I do this?

The code that handles the refreshing:

$scope.setImagePath = function() {
  $scope.imagePath = $scope.camera.endpoint + '?decache=' + Math.random();
};
$scope.setImagePath();

$scope.refreshOnInterval = function() {
  $timeout(function() {
    $scope.setImagePath();
    $scope.refreshOnInterval();
  }, $scope.refresh);
};
$scope.refreshOnInterval();

Upvotes: 0

Views: 538

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

Take a look at the answer of this question. The event demonstrated there would provide the base for an implementation.

My suggestion is use the imageonload directive as a start. Instead of alert-ing something, update a variable with the loaded state of the image. Then, in your $timeout handler, check this state variable and do not call setImagePath() if the state is still loading. You would probably need to update the state variable in setImagePath() too.

Upvotes: 1

Related Questions