using setInterval in angularjs factory

user183123 picture user183123 · Jan 9, 2013 · Viewed 39.6k times · Source

I was trying the code given in angularjs docs (given here: http://jsfiddle.net/zGqB8/) It just implements a time factory and uses $timeout to update the time object after each second.

angular.module('timeApp', [])
.factory('time', function($timeout) {
    var time = {};

    (function tick () {
        time.now = new Date().toString();
        $timeout(tick, 1000);  // how to do it using setInterval() ?
    })();

    return time;
});

How would I do it using setInterval() function instead of $timeout() ? I know that one need to use scope.$apply() to enter the angular execution context but how would that work in a factory function? I mean, in a controller, we have a scope, but we don't have scope in a factory function?

Answer

asgoth picture asgoth · Jan 9, 2013

You can use $timeout as an interval.

var myIntervalFunction = function() {
    cancelRefresh = $timeout(function myFunction() {
        // do something
        cancelRefresh = $timeout(myIntervalFunction, 60000);
    },60000);
};

If the view is destroyed, you can destroy it with listening on $destroy:

$scope.$on('$destroy', function(e) {
        $timeout.cancel(cancelRefresh);
});