1

I write some example code about $timeout service.

var myModule = angular.module('timerTest',[]);


        myModule.controller('counting',function($scope,$timeout)
        {
            var timerObject;
            var count =0;

            var countTime = function()
            {
                count++;
                console.log(count);
                $scope.value = count;
                timerObject = $timeout(countTime,1000);
            };

            $scope.startTimer = function()
            {
                console.log('timer start!');
                $timeout(countTime,1000);
            };

            $scope.endTimer = function()
            {
                console.log('End Timer');
                $timeout.cancel(timerObject);
            };

        });

In that code at countTime function, when I wrote

timerObject = > $timeout(countTime(),1000);  

It calls countTime() very fast so It will make callstack overflow.
But when I wrote

timerObject = $timeout(countTime,1000);

It works perfectly. Is any different from that?

1 Answer 1

2

timerObject = $timeout(countTime(),1000) immediately calls countTime on that line, and passing the result of this into $timeout. Whenever you put parentheses after a function name, it means you're calling the function right there and then - since you're doing this in every iteration of your function, it's causing it to endlessly repeat, hence the stack overflow.

timerObject = $timeout(countTime,1000), on the other hand, passes the countTime function itself into $timeout - this is the correct way to use the service, and will cause $timeout to call countTime after approximately 1000 milliseconds.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for perfectly answer!
@JaeyoungLee - Glad I could help! I feel like this trips people up pretty often.

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.