Asynchronous vs. Synchronous

Asynchronous programming consists of when a unit of work runs separately from ts main application thread and notifies the calling thread to its completion, failure or success. JavaScript is a great example of an asynchronous programming language. It can work line by line like how synchronous programming works, but also can be asynchronous in many ways.

Here’s how:

setTimeout(function(){
  console.log('Hey, why am I last?');
}, 0);

function sayHi(){
  console.log('Hello');
}

function sayBye(){
  console.log('Goodbye');
}
sayHi();
sayBye()

 

  1.  JS will parse the entire script as well as search for syntax errors
  2. it sees a setTimeOut function and adds it to the top of the stack
  3. It will get sent to the Web API container and gets popped off the stack
  4. Timer is set to 0 seconds, therefore, Web API queue sends it to Callback Queue.
  5. event loop will check to see it’s empty. it’s not because there are two functions
  6. function sayHi() will execute, it will console.log ‘Hello’
  7. console.log ‘Hello’ will get popped off the call stack
  8. function sayBye() will execute, adding console.log ‘Goodbye to top of stack
  9. That also executes and gets popped off the stack
  10. anonymous function also gets popped off the stack after getting executed.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s