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();
});
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);
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With