Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在angular.js中,不带()的函数调用与带()的函数调用不同吗?_Javascript_Angularjs_Timeout - Fatal编程技术网

Javascript 在angular.js中,不带()的函数调用与带()的函数调用不同吗?

Javascript 在angular.js中,不带()的函数调用与带()的函数调用不同吗?,javascript,angularjs,timeout,Javascript,Angularjs,Timeout,我编写了一些关于$timeout服务的示例代码 var myModule = angular.module('timerTest',[]); myModule.controller('counting',function($scope,$timeout) { var timerObject; var count =0; var countTime = function()

我编写了一些关于
$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);  
timerObject = $timeout(countTime,1000);
它调用
countTime()
的速度非常快,因此会导致调用堆栈溢出。
但是当我写的时候

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

它工作得很好。与此不同吗?

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


timerObject=$timeout(countTime,1000)
,另一方面,将
countTime
函数本身传递到
$timeout
-这是使用服务的正确方式,将导致
$timeout
在大约1000毫秒后调用
countTime

谢谢您的完美回答@Jaeyoungle-很高兴我能帮上忙!我觉得这经常会让人绊倒。