kidwon
kidwon

Reputation: 4524

When an execution opening occurs

Javascript is a single thread when executing. So a piece of code is executed when there's free resource. However what is a piece of code considered?

a statement:

var a = null;

a block

{
   a();
   b();
   c();
}

I wonder when there would be a possible openning for a triggered event callback when the event has occured before the end of f() execution?

function f(){
   a();
   b();
   asyncDef();
   c();
   d();
}

Until f() is execuded or let's say after c() has finished? When will be the first possible opening?

Upvotes: 1

Views: 54

Answers (2)

Patrick
Patrick

Reputation: 6958

A piece of code is both statements and blocks. The best way I can think to explain it: Use Developer Tools in a browser and step through code. The "piece of code" will be all the code you get through when a certain event happens.

If javascript is inline on the page, it is parsed and executed as a "piece of code". When events happen, the callback function is executed as a piece of code.

Once you are in the execution context, everything happens synchronously and an opening won't be available until the piece finishes. For example:

function f () {
  var d = new Date().getTime(),
      later = d + 5000;

  //Execute code as soon as there is an "opening"
  setTimeout(function () {
     alert("There was an opening.");
  }, 0);

  //Simulate work being done for 5 seconds.
  while (d < later) {
     d = new Date().getTime();
  }

  //implicit return here.
}

f();

You can see that the code (the function f in this example) is using resources until d surpasses later variable. The setTimeout pushes the anonymous function onto the event queue and will be executed when the resources are free (mainly after f completes). You can see that the timing is approximately 5 seconds.

Async JavaScript is a short, but very informative book that explains a lot of these workings. John Resig's blog also does a good job of explaining timers (which you can extend the idea for browser events).

Upvotes: 1

cookie monster
cookie monster

Reputation: 10982

Any synchronous flow of code will need to complete before anything asynchronous can execute. In your f() exmaple, the f() will need to entirely complete, including calls to each function inside.

However, if one of those calls triggers something asynchronous, that async code will not delay the rest of f();, nor the current async code that is waiting.

Upvotes: 1

Related Questions