Search code examples
javascriptangularjstimeout

Using $timeout in ng-init to call a function to display shapes every 2 seconds


I'm attempting to use $timeout with Angular 1 to call a function every 2 seconds with ng-init.

ng-init="$timeout(sc.displaySorted(), 2000)"

The sc.displaySorted() is a function that displays 100 sorted shapes onto the DOM. That works on it's own on ng-init, but I haven't been able to figure out out to have it refresh every 2 seconds. I've also tried $route.reload and recursion.

Here is the vm.displaySorted function:

  vm.displaySorted = function() {
//calls generateFunc and pass total of 50 shapes
var allShapes = generateFunc(50);
//calls sortingFunc with argument of all shapes
var sortedShapes = sortingFunc(allShapes);
for(i = 0; i < sortedShapes.length; i++) {
  var shape = sortedShapes[i]
  if(shape.type === "square") {
    vm.shapesToDisplay.push(sortedShapes[i]);
  }
  if(shape.type === "circle") {
    vm.shapesToDisplay.push(sortedShapes[i]);
  }
}

};//end vm.displaySorted


Solution

  • What your are looking for is the $interval service. You can use it like this:

    $interval(displaySorted, 2000)
    

    Notice here that

    • I just put the function, and not the calling of it (no round brackets).

    • You do not do in you view ng-init="$interval(sc.displaySorted, 2000)" because $interval is not available in the view but in the controller (a service injected by AngularJS), so you have to make a function wrapper of the function. See full sample below.

    angular
      .module('app', [])
      .controller('myctrl', function($interval) {
        var vm = this;
        vm.wizard = {
          displaySorted: fnDisplaySorted,
          init: fnInit
        }
    
        return vm.wizard;
    
        function fnInit() {
          $interval(fnDisplaySorted, 2000);
        }
    
        function fnDisplaySorted() {
          console.log('printing');
        }
    
      });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="app" ng-controller="myctrl as ctrl" ng-init="ctrl.init()">
    </div>