JavaScript: From First Steps to Professional

setTimeout

Anjana Vakil

Anjana Vakil

Software Engineer & Educator
JavaScript: From First Steps to Professional

Check out a free preview of the full JavaScript: From First Steps to Professional course

The "setTimeout" Lesson is part of the full, JavaScript: From First Steps to Professional course featured in this preview video. Here's what you'd learn in this lesson:

Anjana discusses creating an asynchronous function by setting a task to a to-do list by running it in a setTimeout function. Asynchronous refers to code that allows a program to have a task be performed alongside the original task (or tasks) without stopping to wait for the task to complete.

Preview
Close

Transcript from the "setTimeout" Lesson

[00:00:00]
>> So now, we need to start talking about something that makes me wanna cry sometimes with JavaScript. I don't know about y'all. But like Cyndi Lauper, time after time in JavaScript, the way time and JavaScript work are complicated. And part of this is gonna be the answer to the question, why is my get random element function not defined when I go into my console when I load this file locally?

[00:00:29]
The answer to that is a complicated answer that we're gonna have to wrap our head around a few things to understand. And at the heart of all of these things is asynchronous or synchronous code in JavaScript. So, I hope everybody is buckled up and has their energy drinks with them and is armed with a lot of self-compassion for this being a difficult thing.

[00:00:54]
Because even folks like myself who've been working with JavaScript for a long time find this like a tricky concept to wrap our heads around. So do not worry if this starts to break our brains a little bit, that means we're doing it right. You could say that time and JavaScript are sort of frenemies.

[00:01:16]
[LAUGH] They have to get along because we live in universe. I mean, I don't totally understand the physics of it, but time exists or at least we've all agreed that it exists, and we all have watches and clocks that say that it exists. And so our programs also have to do things over time, running code takes time.

[00:01:37]
Now, usually, the code that we run in JavaScript is really, really quick. If I do console.log, this will print in a New York minute, and console.log, this will print one New York minute later. Again, we said a New York minute is an instant. We are gonna see this print out pretty much instantaneously in a New York minute, because these are really, really quick operations.

[00:02:03]
So usually, JavaScript can just run straight through our code, executing it line by line by line by line, doing it one thing right after another, or as we sometimes say executing that code synchronously. So one thing after another, one thing at a time. But sometimes we need to do something that takes a long time, maybe we asked JavaScript to run a while loop over a million numbers or something.

[00:02:34]
Or maybe we did some other things that are gonna take a long time, which we can talk about in a minute. And if anybody remembers the theme song to Dawson's Creek, I don't wanna wait for my life to be over before I get to interact with my web browser again.

[00:02:49]
If JavaScript stopped to wait for a long, long, long-running operation because it's running in the web browser, I wouldn't be able to do anything. I wouldn't be able to click on buttons. I wouldn't be able to be seeing other stuff that's supposed to be changing on the page.

[00:03:08]
So we don't wanna wait for JavaScript to be done with something that takes a long time. And the thing about JavaScript is unlike if folks have worked with other programming languages, this might be a term you've heard. But unlike some other programming languages, JavaScript really, there's an asterisk on this.

[00:03:28]
But in general, JavaScript can really only do one thing at a time. A phrase you might have heard is single threaded. We're not gonna get into the technicalities of what that means. But suffice it to say, just like Lady Gaga says in her Telephone song, she says, I cannot text you with a drink in my hand.

[00:03:47]
JavaScript cannot do multiple things at the same time, I cannot have a drink and also text with that hand. Maybe someone really dexterous could, maybe some other programming language could, but JavaScript and I cannot. So JavaScript can really only do one thing at a time. So what happens is when we give JavaScript a task that's gonna take a long time, for example, here in this code, where we've got a console.log statement, that's a New York minute, that doesn't take much time.

[00:04:19]
But then we have a built-in function called setTimeout, which what setTimeout does is it's going to give it a little function, which we call a callback function, similar to our event handlers. When JavaScript, we give it a function, and then we say only run this after somebody clicked on something I attached to listener two.

[00:04:39]
JavaScript is going to do something similar here, where it's gonna take that function and run it after a certain number of milliseconds. So in this case, a 1,000 milliseconds or one second. So, and one second in computer time is forever. So this is gonna take forever as far as JavaScript is concerned.

[00:04:58]
And so if we are then logging something else, what we want is we don't want JavaScript to stop at that setTimeout line and freeze our web browser and make it so we can't do anything else. So what JavaScript does is it takes that timeout function that we gave it and it sort of adds it to, we could think of it like a to-do list, a task list that it has somewhere in its internals that it's remembering stuff it still needs to do.

[00:05:28]
And it's gonna keep trying to run the rest of our program. And say, all right, I'm gonna get to that long task later, at some point. And a task like setTimeout is gonna run asynchronously, meaning at a different time than kind of where it appears in the code.

[00:05:51]
So, synchronous meaning same time, asynchronous meaning not the same time. I find this terminology pretty confusing, so if you do too, we're in the same boat. But the way this is usually used in JavaScript is it means, is this code gonna run kind of as I see it in the program, or is it gonna run at some other point?

[00:06:15]
So let's find out what happens when I run this code here. So if I run this code, let's see what order we get these statements in. You see what happened there? Let's try it again. So because we set a timeout for 1 second, what happened was JavaScript started running our code.

[00:06:40]
This will print first, okay, that seems pretty reasonable, then it added our console.log. This will print third to a to-do list somewhere and said, hey, let me come back to this after one second. Then it kept running our program, and it printed the final line of our code, but the second thing to print.

[00:07:01]
And then it even came back and returned the value of this whole thing, which turned out to be undefined. And then finally, our second was up, and it ran our function and a console.log, this will print third. So that middle line, that runs asynchronously. And the reason that we want JavaScript to work this way is because JavaScript doesn't have the ability like some other languages to text and hold a drink in its hand at the same time.

[00:07:31]
So what we have to do is text or put the drink down on a table somewhere, then send our text, and then pick the drink back up. And this is so that our browser still gets to do stuff. So we can still click on things, and we can still interact with our web pages, even though we know that there's some other thing that we need to do later that's taking a long time.

[00:07:57]
As I said, one of the hardest things in my opinion to understand about JavaScript is how it works this way because it's a kind of a unique model of time. [LAUGH] But some of the things that work asynchronously in JavaScript or that take a lot of time are stuff like waiting for user events.

[00:08:17]
So essentially, what we did with that event handler that we wrote before or the several event handlers that we've seen so far is we gave JavaScript a function to go run at some point later when the user has clicked on the thing we care about, or when the user has moused over the thing.

[00:08:37]
So we wrote the code at a particular point in our program, but that's not necessarily when it's going to execute. It's gonna execute later when something else happens. Other stuff that takes time is asking a user for something, when it says, hey, where do you wanna save this file?

[00:08:56]
Or hey, which file do you wanna upload into this website? Or can I have permission to record from your camera? Things like that, those take time. Another thing that takes time that's gonna be relevant for our doggo game is it takes time to load data from somewhere else on the interwebs.

[00:09:19]
So if we want to, let's say, go find an image somewhere out there on the Internet, it's gonna take a little bit of time for JavaScript to say, okay, you're telling me to go find some image, I'm gonna go get it. I'm gonna make a call to that person who has that image, I'm gonna wait for them to respond to me, and then I'm gonna give you the image back, that's gonna take some time.

[00:09:44]
It has to maybe go all the way around the world to find us the image we want of a doggo that's really special from a different part of the world, I don't know. So that is something that is gonna take a lot of time, and we need to handle asynchronously in JavaScript.

[00:10:01]
So another thing that takes time in JavaScript is learning about asynchronous JavaScript. If you all walk away and have at least your feet under you of like, okay, this is something that I don't totally understand, but I know that I can get it, that is success as far as I'm concerned here.

[00:10:19]
I do not expect you all to walk all right being like, I know everything there is to know about asynchronous JavaScript because that takes a lot of time to really wrap your head around what is happening here. And I haven't even explained really how this works under the hood or why it works this way, but there are some great resources out there.

[00:10:35]
Of course, MDN has a guide on it, but there's also a really, really, really great talk by Philip Roberts about something called the event loop. And yes, event as in click events, and mouse hover events, and whatnot, and anything else that's taking a long time in JavaScript, like our timeout.

[00:10:52]
So I highly recommend as optional homework, you go check that out and read up more on asynchronous JavaScript. There's a lot of other resources courses, there's some courses on Frontend Masters that really go into it and talk about different kind of models of asynchronous programming. So we're gonna talk about it in a very practical sense of how do we do the thing we're trying to do.

[00:11:15]
But in terms of really getting the picture of what JavaScript is doing when it comes to these long-running tasks and how it's managing to text and drink at the same time or at least pretend to, even though we can't really. That's something that's a little bit out of the scope of this course.

[00:11:31]
>> How much time do you allow for asynchronous actions?
>> How much time do you allow? Well, it really depends, which is a frustrating answer to almost every question that it is an answer to, which is a lot in computer science. It depends, but for example, for our setTimeout, which we said we want this to wait 1,000 milliseconds or one second.

[00:11:58]
That means we need to make, we are telling JavaScript to wait 1,000 milliseconds before it even tries to run our little anonymous function, that console.log, and this will print third. Which means it might even take a little bit more than 1,000 milliseconds before JavaScript is able to get to it.

[00:12:18]
Cuz we're basically saying, hey, JavaScript, wait 1000 milliseconds and then try to do this. So we said that what it does is sort of it adds it to a task list, a to-do list kind of that's related to this event loop thing that I'm waving my hands at and telling you to go look up later.

[00:12:36]
It adds this timeout to a task list. But if there's a lot of other stuff on that task list, then it might take it even more than 1,000 milliseconds before it actually gets to run the code. So in terms of how much time we allow, there's not a fixed answer.

[00:12:52]
For example, if I am calling up a server on the other side of the planet, how much time that's gonna take for my browser to send a message across the interwebs to somewhere thousands and thousands and thousands of miles or kilometers away, and then get an answer back, that can depend on a lot of things.

[00:13:13]
It can depend on what the person who built that website that I'm talking to did on their end, how fast it is, how slow it is. Could depend on whether a shark has not chewed through a trans-oceanic data cable somewhere. It can depend on a lot of things.

[00:13:32]
So there's not really a hard and fast answer.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now