Asynchronous Javascript For Beginners (pt. 1)

Okay, no use beating around the bush. Asynchronous JS. What is is?

Probably the opposite of Synchronous JS, right? Let’s start there. Okay, what does ‘synchronous’ make you think of? Things happening at the same time. Synchronized swimmers. A team of bank robbers looking at their watches and yelling “Sync!” Stuff happening simultaneously. Which would make ‘async’ refer to things happening NOT at the same time. Right? Turns out, wrong.

Turns out, the definition is almost completely opposite. ‘Synchronous’ in programming doesn’t mean ‘at the same time’, but rather ‘one at a time, one after another.’ Synchronous programming just means that a series of events occur, and they occur in order:

  1. Thing 1 happens
  2. Thing 2 happens
  3. Thing 3 happens
  4. Thing 4 happens

Okay. So we’ve defined synchronous as one after another. Asynchronous code, on the other hand, will refer to code that starts running, and then for some reason has to stop in the middle, at which point later processes just start running AS IF that earlier thing was already done doing its thing. THEN, once that earlier process is ready to finish what it was doing, it picks up where it left off and finishes up.

  1. Thing 1 happens
  2. Thing 2 starts doing its thing and then is all like “Oh damn I actually can’t finish this right now, you guys go on without me”
  3. Thing 3 happens
  4. Thing 4 happens
  5. Thing 2 is like “Okay whew, I’m ready now” and finishes doing its thing.

So that’s Asynchronous Javascript. But what kind of things could Thing 2 be, that it needs to take so long to finish? This obviously isn’t just a list of console.logs, one after another. Here’s a list of things that make your code async, lifted from Byte Archer’s terrific post:

  • timer functions setTimeoutsetInterval
  • special functions nextTicksetImmediate
  • listening to network, querying a database
  • reading or writing, generally I/O from a resource
  • subscribing to an event

If you don’t want to go to far down the rabbit hole right now, just remember that the following two things are asynchronous: setTimeout( ) and AJAX.

If you play around a bit with setTimeOut( ) it won’t take long for you to see this in action. If you do a setTimeOut( ) with a console.log in it, followed by several other console.logs, you’ll see that the later ones don’t wait up for the async one, they just happen first.

We’ll pick up with Ajax in part 2.

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 )

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