difference between countUp() and countUp [duplicat

2019-08-24 06:20发布

I have a script that counts up the number in a box (actually, in this exercise -> http://jqexercise.droppages.com/#page_0022_ ) each 1 second like this.

var target = $("#target input");
var countUp = function(){
    target.val(parseInt(target.val())+1);   
        setTimeout(countUp,1000);          // this line
};

countUp();

My questions is, when i change countUp to countUp() at the line I marked with // this line, it instantly counts up to 15616. What is the difference between those?

4条回答
乱世女痞
2楼-- · 2019-08-24 06:28

countUp references the function as an object. In JavaScript everything is an object, including functions, and can be passed around. countUp() calls the function countUp and returns its value.

查看更多
女痞
3楼-- · 2019-08-24 06:30

In a nutshell, the setTimeout(countUp, 1000); sets the time to execute the countup function in milliseconds seconds every nth second. Which in this case would be 1 second. countup is just being passed as a parameter into the setTimeout function here.

查看更多
老娘就宠你
4楼-- · 2019-08-24 06:47

countUp() is a recursive invocation of the function. Each call to the function invokes it again (immediately), and the return value (which is undefined) is passed to setTimeout.

This would be an infinite loop, except I believe the exception from setTimeout receiving a non function is interrupting it after 1 second, leading to a stop at 15616.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-08-24 06:48

Adding the () to the function invokes it instantly, while just using the function name is actually passing it as a parameter.

查看更多
登录 后发表回答