简体   繁体   中英

In angular.js , Is function call without () different from call with()?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM