Stop Low Resolution Sign

Transcript

Tutorial Area

Transcript of the tutorial.

TOP
Tutorial
          Okay then.

So hopefully now you understand at least the basic principle of asynchronous code and how JavaScript

has a single thread and runs through one function at a time or one statement at a time.

So I want to do a quick demo of this in action, a very quick, simple one.

So the first thing I'm going to do is paste in four console logs.

So if I save this, we know now that JavaScript is going to execute these one at a time from top to

bottom.

And in the console we get one, two, three, four, as expected.

Now what I'm going to do in the middle is I'm going to do a set timeout and we've seen this before.

It's where we pass in a function and that function fires after a certain amount of time that we specify.

So let's do the function, first of all, and inside here we'll console dot log and we'll say the callback

function fired.

Okay.

And we want to fire this after well, let's just say 2000 milliseconds.

So that's two seconds.

So this right here, this is meant to emulate some kind of network request that takes time to do so.

Imagine this is going out to get data and it takes two seconds to do.

Then when it comes back, it's going to fire a callback function.

It's the same kind of thing.

In this case, we're not getting data, we're just waiting two seconds to emulate that request and then

we're firing this.

So this right here, this is asynchronous code in action.

It's going to start when the file runs.

It's going to wait two seconds and then it's going to finish later by firing this callback function.

Now, is this going to block the rest of the code?

Will it go one, two, then wait two seconds and fire this, then three, four, or will it not block

the code?

Well, I just said that this is asynchronous, so it doesn't block the code.

And I'll show you that if I save it, we'll see.

One, two, three, four.

Then after two seconds, we get this.

So if you imagine that image of a thread I showed you before and these things are on it, it fires this,

then this, then this, and then it waits two seconds over here and passes the callback function somewhere

else.

And then it fires this, then this.

And after two seconds, the callback function is added to the bottom over here.

And this is where it fires at the end.

After one, two, three, four.

So this does not block the code.

So in the future, instead of using set timeout, we'll be using real Http network requests for data.

But this kind of sets the scene of how it all works.

It will be the same principle.

So now we know the general principle behind it of asynchronous code.

I'm going to show you how to actually make network requests.