well i m beginner in angularjs and ionic framework,
what i want to do is that i want to get user location after each 5 minutes so i need to use a function on time interval but i want to use it globally means not at just controller level. it is like it will be called after each 5 minutes automatically doesnt matter to in which controller we are.
I would do it stil on controller level.
In most cases you have a “main controller” wrapped around your content like a controller on the body tag.
Or if you have an abstract base-state you could connect this state with this controller.
Maybe it would be nice to build this factory like an own class where you can create instances of… to provide the possibility to handle multiple intevals ;).
If i understand your code correctly, you will overwrite your “clock” everytime you start a new interval.
Yes… In fact this is an (over)simplification of what I do in my code.
If you start multiple timers, it can have some performance issues and all your clocks are not sync (quite ugly for user !).
So it’s interesting to have just one clock for multiple timers.
Here is my full code :
.factory('ClockSrv', function($interval){
'use strict';
var service = {
clock: addClock,
cancelClock: removeClock
};
var clockElts = [];
var clockTimer = null;
var cpt = 0;
function addClock(fn){
var elt = {
id: cpt++,
fn: fn
};
clockElts.push(elt);
if(clockElts.length === 1){ startClock(); }
return elt.id;
}
function removeClock(id){
for(var i in clockElts){
if(clockElts[i].id === id){
clockElts.splice(i, 1);
}
}
if(clockElts.length === 0){ stopClock(); }
}
function startClock(){
if(clockTimer === null){
clockTimer = $interval(function(){
for(var i in clockElts){
clockElts[i].fn();
}
}, 1000);
}
}
function stopClock(){
if(clockTimer !== null){
$interval.cancel(clockTimer);
clockTimer = null;
}
}
return service;
})
With this service, you can have as many timers as you want, with just one clock and they are all sync !
This service only handle clocks with 1 second delay but that’s only what I need. If you need more, you can complexify it by having an array of clockTimers and an array of array of clockElts with each requested interval…