在angular.js中,函数调用没有()与调用()不同吗?

时间:2016-03-12 12:58:58

标签: javascript angularjs timeout

我写了一些关于$timeout服务的示例代码。

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);
            };

        });

countTime函数的代码中,当我写

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

它会非常快地调用countTime(),因此会使callstack溢出 但是当我写作

timerObject = $timeout(countTime,1000);

完美无缺。有什么不同吗?

1 个答案:

答案 0 :(得分:2)

timerObject = $timeout(countTime(),1000)立即在该行上调用countTime,并将结果传递给$timeout。每当你将括号放在一个函数名后面时,就意味着你正在那里调用函数然后 - 因为你在函数的每次迭代中都这样做,它会导致它无休止地重复,因此堆栈溢出。

另一方面,

timerObject = $timeout(countTime,1000)countTime函数本身传递给$timeout - 这是使用该服务的正确方法,并会导致$timeout调用大约1000毫秒后countTime