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)
In 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:
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:
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 upcoming events, what is the internal clock resolution, etc.)[*] You can achieve similar behaviour by using
setInterval()
once.