Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a function from $interval in angularjs

I wanted to call a function from $interval's timeout.

angular.module('myApp').factory('myFactory',function($interval){

    var stop;
    return{
        start : function() {
            if(angular.isUndefined(stop)){
                stop = $interval(function() {
                        function1();
                    }
                    ,  30000);
            }
        },

        function1 : function() {
            console.log('In function1');
            function2();
        },

        function2 : function() {
            console.log('In function2');
        }

    }
});

error I am getting is

TypeError: undefined is not a function

Please let me know what could be the reason and how to solve the same

Thanks, ng-R

like image 383
ng-R Avatar asked Jun 12 '26 03:06

ng-R


1 Answers

My advise it move definition of your functions outside return object please see demo below

var app = angular.module('app', []);
angular.module('app').factory('myFactory', function($interval) {

  function start() {
    $interval(function() {
      function1();
    }, 3000);
  }


  function function1() {
    console.log('In function1');
    function2();
  }

  function function2() {
    console.log('In function2');
  }




  return {
    start: start,
    function1: function1,
    function2: function2
  };
});
app.controller('homeCtrl', function($scope, myFactory) {



  myFactory.start();


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body>
  <div ng-app="app">
    <div ng-controller="homeCtrl">


    </div>
  </div>
</body>
like image 182
sylwester Avatar answered Jun 14 '26 03:06

sylwester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!