最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Priority of function execution in javascript - Stack Overflow

programmeradmin0浏览0评论

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 time a is called. – user1106925 Commented Jun 7, 2012 at 13:00
Add a ment  | 

3 Answers 3

Reset to default 7

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 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.

发布评论

评论列表(0)

  1. 暂无评论