how do i display an alert when a request is longer than 30 seconds?

You can use a promise $q, since promises can only be resolved once, and cannot be resolved after having been rejected. In this example, use the input to specify the wait time in seconds, before the request is completed. An alert is shown after 5 seconds if the request has not completed by then.

angular.module("app", [])
  .controller("ctrl", function($scope, $timeout, $q) {
    $scope.wait = 0;

    $scope.request = function() {
      const timer = $q.defer();
      
      timer
        .promise
        .then(function(value) {
          alert(value);
        })
        // do nothing
        .catch(() => {});
      
      $timeout(function() {
        timer.resolve("Request takes too long");
      }, 5000);
      
      $timeout(function() {
        // Here your request resolves successfully
        console.log("Resolving request");
        timer.reject();
      }, $scope.wait * 1000);
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <input type="number" ng-model="wait">
  <button ng-click="request()">Click</button>
</div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top