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);
};
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);
};
$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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With