Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire a AJAX request every second in AngularJS using $interval

The interval function keeps on looping in the last element that I click. What I want to happen is to cancel the last interval when I click on a new element and start all over again when I click it. I clicking on each item in ng-repeat.

This is my code.

$scope.onClickTab= function(x,tkid, sid, $event){
      var vtpostdata = 'TokenId=' + tkid +
                                ',SessionId=' + sid +
                                ',ChatMessageCount=' + 0 +
                                ',retrytimes=' + 10 +
                                ',delayms=' + 100;
  $interval(function() {
      $http.jsonp(ServiceDomainSite + 'myApi' + vtpostdata + '?callback=JSON_CALLBACK&t=' 
                                    + new Date().getTime())
            .success(function (data) {
              var resultObject = angular.fromJson(data.Rows);
              $scope.Chats = resultObject;    
            });
  }, 1000);
};
like image 955
John Wick Avatar asked Mar 18 '26 05:03

John Wick


2 Answers

Nice and fine with $interval.cancel(). I also removed var vtpostdata because it is not used in the code untill your $http request again. So there is no need to create a var at this point. Also check the documentation of AngularJS $interval to learn more about $interval handling.

var myInterval = null;

$scope.onClickTab = function(x,tkid, sid, $event){

    //cancel current interval
    if (myInterval !== null) {
        $interval.cancel(myInterval);
    }

    myInterval = $interval(function() {
        $http.jsonp(ServiceDomainSite + 'myApiTokenId=' + tkid +
        ',SessionId=' + sid +
        ',ChatMessageCount=' + 0 +
        ',retrytimes=' + 10 +
        ',delayms=' + 100 + '?callback=JSON_CALLBACK&t='
        + new Date().getTime()).success(function (data) {
            var resultObject = angular.fromJson(data.Rows);
            $scope.Chats = resultObject;
        });
    }, 1000);
};
like image 157
lin Avatar answered Mar 19 '26 17:03

lin


$interval service returns a promise which can be canceled at any time so you can use them as per official documentation. For Eg.

var stopTime = $interval(function(){}, 1000);

and for canceling just use

$interval.cancel(stopTime);

https://docs.angularjs.org/api/ng/service/$interval

like image 34
Arun Redhu Avatar answered Mar 19 '26 19:03

Arun Redhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!