admin管理员组文章数量:1304088
I don't understand why a second function call ( after a function body ) has a priority over the one inside of a body ?
function a(){
var num = 5;
console.log( ++num );
setTimeout( a, 100 );
};
setTimeout(a,2000)
I don't understand why a second function call ( after a function body ) has a priority over the one inside of a body ?
function a(){
var num = 5;
console.log( ++num );
setTimeout( a, 100 );
};
setTimeout(a,2000)
Share
Improve this question
edited Feb 7, 2019 at 3:05
Joshua
43.3k9 gold badges78 silver badges149 bronze badges
asked Jun 7, 2012 at 12:49
Miroslav TrninicMiroslav Trninic
3,4514 gold badges31 silver badges55 bronze badges
4
- 2 What behaviour do you expect? – Sirko Commented Jun 7, 2012 at 12:52
- Were you supposed to write "function a() {...}();" (note the final parentheses)? Your code doesn't call the function before the final line. – tsiki Commented Jun 7, 2012 at 12:54
- I just want to know why one call is waiting for the other ? Then I'll be able to predict behaviour. – Miroslav Trninic Commented Jun 7, 2012 at 12:55
-
Are you confused by the fact that
num
never seems to change? If so, it's because you're reinitializaing a new variable every timea
is called. – user1106925 Commented Jun 7, 2012 at 13:00
3 Answers
Reset to default 7In chronological order:
you are defining function
a
without calling ityou are scheduling
a
to be invoked after two seconds:setTimeout(a,2000)
it is called
when it is called, it schedules itself for invocation after 100 milliseconds
Your code basically sleeps for 2 seconds and then executes a
with 100 millisecond pauses[*].
However judging by your context you are asking what is the priority in the following situation:
setTimeout(a, 2000);
setTimeout(b, 100);
Well, most likely b
will be called first (assuming there is no unpredictable pause between first and second line, e.g. due to overall OS performance problem).
If you use the same timeouts:
setTimeout(a, 100);
setTimeout(b, 100);
a
will most likely be called first. However I don't think this is guaranteed and depends on the JS engine (whether it uses a strict FIFO list for uping events, what is the internal clock resolution, etc.)
[*] You can achieve similar behaviour by using setInterval()
once.
The function a
isn't called, just defined. The piece of code that is actually run is the definition of a
, then setTimeout(a,2000)
is called.
I think
function a () {
var num = 5;
console.log( ++num );
setTimeout( a, 100 );
};
is a function body and after this we are calling. I do not think it is a hierarchy problem.
本文标签: Priority of function execution in javascriptStack Overflow
版权声明:本文标题:Priority of function execution in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741779825a2397241.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论