Priority of function execution in javascript

8.3k views Asked by At

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)
3

There are 3 answers

2
Tomasz Nurkiewicz On BEST ANSWER

In chronological order:

  • you are defining function a without calling it

  • you 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 upcoming events, what is the internal clock resolution, etc.)

[*] You can achieve similar behaviour by using setInterval() once.

0
MaxArt On

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.

0
Naveen On

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.