difference between countUp() and countUp [duplicate]

柔情痞子 提交于 2019-12-13 05:26:10

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/16949879/difference-between-countup-and-countup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!