3

I'm writing an angularjs controller that's is polling for stuff. The polling function calls itself with a timeout. Below are two examples of this. The first exceeds the call stack size, but the second example does not. Why is that?

Example 1 (Exceeds call stack size):

myApp.controller('Ctrl1', function($scope, $timeout) {
   $scope.value = 1;
    function poll() {
        $scope.value++;
        $timeout(poll(), 1000);
    }
   poll();
});

Example 2 (works fine):

myApp.controller('Ctrl1', function($scope, $timeout) {
   $scope.value = 1;
    function poll(){
        $timeout(function() {
            $scope.value++;
            poll();
        }, 1000);
    };     
   poll();
});

2 Answers 2

6

You're not passing the function but its returned value (undefined). Which means you immediately call it and as it calls itself, well, here's your stack overflow.

Change

$timeout(poll(), 1000);

to

$timeout(poll, 1000);

As an aside, you can rewrite

function poll() {
    $scope.value++;
    $timeout(poll, 1000);
}
poll();

in a slightly more elegant manner which doesn't pollute the external scope :

(function poll() {
    $scope.value++;
    $timeout(poll, 1000);
})();
Sign up to request clarification or add additional context in comments.

Comments

0

Put function in side $timeout(): Sou make it like:

$timeout(function(){

   pool();
   // You can also add some other things here...

}, 1000):

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.