Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using setInterval in angularjs factory

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?

like image 860
user183123 Avatar asked Jan 09 '13 14:01

user183123


People also ask

What is $interval in Angular JS?

AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing. The $interval service executes the specified function on every specified milliseconds duration.

What does setInterval () method do in JS?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.

How does the setInterval () function work in?

setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

How do you run setInterval 5 times?

“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.


2 Answers

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); }); 
like image 171
asgoth Avatar answered Sep 22 '22 07:09

asgoth


Update

Angular has implemented an $interval feature in version 1.2 - http://docs.angularjs.org/api/ng.$interval


Legacy example below, disregard unless you're using a version older than 1.2.

A setInterval implementation in Angular -

I've created a factory called timeFunctions, which exposes $setInterval and $clearInterval.

Note that any time I've needed to modify scope in a factory I've passed it in. I am unsure if this meets the "Angular way" of doing things, but it works well.

app.factory('timeFunctions', [

  "$timeout",

  function timeFunctions($timeout) {
    var _intervals = {}, _intervalUID = 1;

    return {

      $setInterval: function(operation, interval, $scope) {
        var _internalId = _intervalUID++;

        _intervals[ _internalId ] = $timeout(function intervalOperation(){
            operation( $scope || undefined );
            _intervals[ _internalId ] = $timeout(intervalOperation, interval);
        }, interval);

        return _internalId;
      },

      $clearInterval: function(id) {
        return $timeout.cancel( _intervals[ id ] );
      }
    }
  }
]);

Example Usage:

app.controller('myController', [

  '$scope', 'timeFunctions',

  function myController($scope, timeFunctions) {

    $scope.startFeature = function() {

      // scrollTimeout will store the unique ID for the $setInterval instance
      return $scope.scrollTimeout = timeFunctions.$setInterval(scroll, 5000, $scope);

      // Function called on interval with scope available
      function scroll($scope) {
        console.log('scroll', $scope);
        $scope.currentPage++;

      }
    },

    $scope.stopFeature = function() {
      return timeFunctions.$clearInterval( $scope.scrollTimeout );
    }

  }
]);
like image 36
BradGreens Avatar answered Sep 19 '22 07:09

BradGreens