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.