What is the difference in between:

k = setInterval(function(){loop();},100);

and

k = setInterval(loop(),100);

Why does the second one run once, like the setTimeout() function and the first one every 1/10 of a second?

有帮助吗?

解决方案

In second one you are actually executing loop before setInterval is called, so you are passing result of the loop to the setInterval

More similar would be

k = setInterval(function(){loop();},100);

k = setInterval(loop,100);

其他提示

first example allows you to do some work before calling loop and to pass some arguments if necessary

second one requires a function object as a 1st parameter and you cannot pass anything inside the brackets.

1st one is more widely spread pattern than 2nd (which is a little bit obsolete)

Lets checkout how doest JS run this code:

Fist way -

JS see setInterval - it should have 2 arguments and timer - in first variant everythink is trivial - you passed a function to be called on each interval and timer.

Lets check second variant - again setInterval, 2 params . But this time you dont pass link to function but called function and the result of this function will be passed to the setInterval. As you called function - it runs once, as it doesent return function setInterval cant run anything.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top