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-很高兴我能帮上忙!我觉得这经常会让人绊倒。