Use Timer In Angularjs - angularjs

I am Creating a web app
on my button click there is an insert query if after (15 seconds) it is unable to insert, it should show the message (in alert) the internet connection is very slow Please Wait For A While
How To Use timer in angularjs?

Instead if $timeout, IMO $interval will be of more help.
Below is the sample snippet for doing the same
function FetchCtrl($scope, $http, $interval) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.count = 0;
var stop;
var stopInterval = function(){
$interval.cancel(stop);
stop = undefined;
$scope.count=0;
}
$scope.fetch = function() {
stop = $interval(function(){
$scope.count++;
if($scope.count === 15){
//showAlert here
stopInterval();
}
},1000);
$http({method: $scope.method, url: $scope.url})
.success(function(data, status) {
stopInterval();
$scope.status = status;
$scope.data = data;
})
.error(function(data, status) {
stopInterval();
$scope.status = status;
$scope.data = "Request failed";
});
};
$scope.$on('$destroy', function() {
// Make sure that the interval is destroyed too
stopInterval();
});
}
Here the interval is started as soon as http request is made, it updates the counter every second for 15 seconds. Then once 15 is reached, alert is shown and the interval is stopped.
If the request is completed, then also the interval is stopped.
PS: While using $interval, one thing should be kept in mind : Cancel the interval when scope is destroyed otherwise it will continue to execute callback even when we have moved out of that controller scope.

Related

Cancelling $interval.cancel based on id passed in $interval.timer

In the below given code, we are calling startTimer function , where we use $interval to trigger the request to backend until we get the data.status == "complete" ;and once status is completed ,we set the flag = true and flag will lead to trigger the watch and it calls the $scope.stop function to cancel the timer using $interval.cancel.
But here issue arises i.e. , $interval.cancel doesn't know which timer to stop first.
When there are multiple request to call the timer based on id, the completed timer based on that id should get cancelled.
So my question is How to cancel the timer based on the id.
angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval',
function($scope, $interval) {
var timer;
var time = 10;
$scope.countdown = time;
$scope.startTimer = function(id) {
timer = $interval(function(id) {
$scope.countdown--;
//res is response from my backend
someRestService(id).then(res);
var data = res;
if (data.status = "complete") {
$scope.timerFlag = true;
}
}, 15000);
};
}
$scope.stopTimer = function() {
$interval.cancel(timer);
};
$scope.$watch() {
if ($scope.timerFlag == true) {
$scope.stopTimer();
}
}
]);
scenario :
RestapiHit/627
RestapiHit/628
RestapiHit/629
it will call the 627 request and finish the process and then when about to cancel using $interval.cancel it goes for latest one and cancel the 629 but not 627
Take a look at:
angular.module('timerApp', ['timerApp.controllers']);
angular.module('timerApp.controllers', []).controller('timerController', ['$scope', '$interval',
function($scope, $interval) {
var timer= {} ;
var time = 10;
$scope.countdown = time;
$scope.startTimer = function(id) {
timer[id] = $interval(function(id) {
$scope.countdown--;
//res is response from my backend
someRestService(id).then(res);
var data = res;
if (data.status = "complete") {
$scope.stopTimer(id);
}
}, 15000);
};
}
$scope.stopTimer = function(id) {
$interval.cancel(timer[id]);
delete timer[id];
};
]);
Right now, you just have one timer value assigned as it is declared at controller level. But since, you might have multiple calls for $interval so i think this approach should work better.

angularJS $timeout function used and page reloading on service calls

I have used $timeout to call an angular JS service in every 5 seconds. But it leads to a page or cursor reload in my application. Can anyone assist me to stop the page reload?
var app = angular.module('myApp', ['ngAnimate']);
app.controller('MainCtrl', function($scope, $http, $timeout) {
var loadTime = 1000, //Load the data every second
errorCount = 0, //Counter for the server errors
loadPromise; //Pointer to the promise created by the Angular $timout service
var getData = function() {
//console.log('http://httpbin.org/delay/1?now=' + Date.now());
$http.get('http://httpbin.org/delay/1?now=' + Date.now())
.then(function(res) {
$scope.data = res.data.args;
errorCount = 0;
nextLoad();
})
.catch(function(res) {
$scope.data = 'Server error';
nextLoad(++errorCount * 2 * loadTime);
});
};
var cancelNextLoad = function() {
$timeout.cancel(loadPromise);
};
var nextLoad = function(mill) {
mill = mill || loadTime;
//Always make sure the last timeout is cleared before starting a new one
cancelNextLoad();
loadPromise = $timeout(getData, mill);
};
//Start polling the data from the server
getData();
//Always clear the timeout when the view is destroyed, otherwise it will keep polling and leak memory
$scope.$on('$destroy', function() {
cancelNextLoad();
});
$scope.data = 'Loading...';
});
Check to make sure loadPromise exists before cancelling it:
var cancelNextLoad = function() {
̶$̶t̶i̶m̶e̶o̶u̶t̶.̶c̶a̶n̶c̶e̶l̶(̶l̶o̶a̶d̶P̶r̶o̶m̶i̶s̶e̶)̶;̶
loadPromise && $timeout.cancel(loadPromise);
};

Angular two way binding not working

I'm very new to angularjs and I want to establish a connection to my server and dynamically show the result to user. so far I've tried:
angular.module('myApp.controllers', []).controller('socketsController', function($scope) {
$scope.socket = {
client: null,
stomp: null
};
$scope.reconnect = function() {
setTimeout($scope.initSockets, 10000);
};
$scope.notify = function(message) {
$scope.result = message.body;
};
$scope.initSockets = function() {
$scope.socket.client = new SockJS('/resources');
$scope.socket.stomp = Stomp.over($scope.socket.client);
$scope.socket.stomp.connect({}, function() {
$scope.socket.stomp.subscribe('/user/topic/messages', $scope.notify);
});
$scope.socket.client.onclose = $scope.reconnect;
};
$scope.initSockets();
});
But when I use {{result}} nothing appears.
UPDATE
The server response is totally right with console.log(message.body).
I guess, the callback is not taking the scope properly. Try call $scope.$apply(); after you attach the message.body to result :
$scope.notify = function(message) {
$scope.result = message.body;
$scope.$apply();
};
$scope.$apply() triggers an angular digest cycle whcih will update all the bindings..
Call it inside a timeout function but inject $timeout first it will call the digest cycle and update the value.
$timeout(function(){
$scope.result = message.body;});

AngularJs & Ionic : Stop/Restart $timeout when change and return to view

I have a View that is updated after 1 minute, I stop the timer after before leaving this view, and all is OK.
After returning to the current view the timer don't restart again.
This is the code of the controller of this view:
.controller('IndexCtrl', function($scope, $timeout, RestService) {
var updateN = 60*1000;
$scope.test = "View 1 - Update";
var update = function update() {
timer = $timeout(update, updateN);
/** make a http call to Rest API service and get data **/
RestService.getdata(function(data) {;
$scope.items = data.slice(0,2);
});
}();
/** Stop the timer before leave the view**/
$scope.$on('$ionicView.beforeLeave', function(){
$timeout.cancel(timer);
//alert("Before Leave");
});
/** Restart timer **/
$scope.$on('$ionicView.enter', function(){
$timeout(update, updateN);
//alert("Enter");
});
})
.controller('ViewCtrl2', function($scope) {
$scope.test = "View 2";
});
I resolve the problem,
There is not a problem with the cache, but with the function update that is not called after I re-enter on the page.
I move the update function inside the $ionicView.enter :
The corrected code is:
$scope.$on('$ionicView.beforeLeave', function(){
//updateN=12000000;
$timeout.cancel(timer);
//alert("Leave");
});
$scope.$on('$ionicView.enter', function(){
//updateN=12000000;
var update = function update() {
timer = $timeout(update, updateN);
RestService.getdata(function(data) {
//console.log(tani);
//$scope.items = data;
$scope.items = data.slice(0,2);
});
}();
});
When you go back to current view, it comes from the cache, so the controller does not work again. You can disable caching in the config section of your app by adding this line of code :
$ionicConfigProvider.views.maxCache(0);
or you can disable cache on a specific view in the routing part by addding
cache : false property.
More information here and here
In your code your controller function does not call on change of view. call $timeout function outside of var update function. Each time view loads it call its controller and call anonymous or self executing functions in their scope.
.controller('IndexCtrl', function($scope, $timeout, RestService) {
var updateN = 60 * 1000;
$scope.test = "View 1 - Update";
var update = function update() {
var timer = $timeout(update, updateN);
/** make a http call to Rest API service and get data **/
RestService.getdata(function(data) {;
$scope.items = data.slice(0, 2);
});
}();
/** Stop the timer before leave the view**/
$scope.$on('$ionicView.beforeLeave', function() {
$timeout.cancel(timer);
//alert("Before Leave");
});
/** Restart timer **/
$scope.$on('$ionicView.enter', function() {
timer()
});
})
.controller('ViewCtrl2', function($scope) {
$scope.test = "View 2";
});

AngularJS service with promise - reload/refresh

first of all, i'm a noob to AngularJS - hope someone can help with this one. I really don't get it..
I have a AngularJS app, with a "service" that return a promise, that works all well, but the problem is, if my app at the beginning is offline, and afterward gets online, now I want the service promise to refresh.
If my app is online at the beginning, it all works well.
But if it is offline, and later gets online, and the reload button is clicked - the alert("TEST TEST"); never gets executed :(
.service('webService', function ($http, $q, $timeout){
var webservice_url = "http://mywebservice_url";
var deferred = $q.defer();
var service = {};
service.refresh = function() {
$http.get(webservice_url+"?action=get_settings", {timeout: 2000})
.success(function(data) {
deferred.resolve(data);
})
.error(function(err) {
deferred.reject({'error': err});
});
return deferred.promise;
}
this.refresh = function() {
this.promise = service.refresh();
return this.promise;
}
this.promise = service.refresh();
})
.controller('NetworkCtrl', function($scope, $location, $timeout, webService) {
$scope.reloadClick = function(){
webService.refresh().then(function(data) {
alert("TEST TEST");
console.log(data);
});
}
})
I am not 100% positive... cause I can't run your code... but I think that moving line three into the service.refresh method, that should get you closer.

Resources