Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive javascript exceeding call stack size

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();
});
like image 796
bfw Avatar asked Nov 24 '25 23:11

bfw


1 Answers

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);
})();
like image 195
Denys Séguret Avatar answered Nov 26 '25 11:11

Denys Séguret



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!