Check out a free preview of the full Vanilla JavaScript Projects course:
The "Dates & Times" Lesson is part of the full, Vanilla JavaScript Projects course featured in this preview video. Here's what you'd learn in this lesson:

Anjana explores the Date object and its various methods for representing and manipulating time. The setTimeout and setInterval functions create delays and intervals in code execution. Questions about how the event loop handles the execution of async code, setTimeout, and setInterval are also discussed.

Get Unlimited Access Now

Transcript from the "Dates & Times" Lesson

[00:00:00]
>> So what about other stuff that the browser knows? How about, does it know what time it's [LAUGH] any BoJack correspond fans? [LAUGH], what time is it now .com? Okay, [LAUGH], the browser has a concept of time, which gives JavaScript a concept of time. But we're gonna be putting a pin in this for a little bit later.

[00:00:23] There is a capital D date object, everything is an object. We'll talk about that more later, too. That we can use with the new constructor to get an instance of a date. A little preview of some object-oriented programming, which represents the current moment in this thing we call time.

[00:00:50] And the date object that I get from calling new Date comes with some handy-dandy tools. For example, we have date to string on objects. Well, in this case, we have a special one called, toDateString, which gives me a kind of high-level overview. If it's a Tuesday, it's November 20th, etc.

[00:01:12] And then we also get a toLocaleDateString, which knows that I have my browser set to English US locale, and in the US we put the month, and then a slash. And then the day, and then a slash, and then the year, even though the rest of the world thinks that that's bonkers.

[00:01:37] [LAUGH], in any case, you'll also see that used a lot in sites where you know you have an international audience. And you wanna make sure you're displaying things in their expected format, because otherwise those early periods of the year get very confusing for the international crowd. Okay, so also without the new constructor we can call a method on the capital D date object called now, we can call Date.now, and it gives us the very helpful value of one trillion or something milliseconds.

[00:02:20] Yeah, all of my refs are this dated. Okay, [LAUGH], the ridiculously large and unhelpful number there is milliseconds since the epoch, which we could have a whole other course on talking about how that all happened. But in any case, it's basically, a number of milliseconds that computers can interpret and figure out what that corresponds to in something resembling human time.

[00:02:52] I say this with a lot of caveats because time is a construct. We're all experiencing it differently and computers think that everything is happening right now. So, anyway, we can, however, use this very unhelpful human readable value for helpful things like timing stuff. So, for example, if I grab Date.now as the start and then I do some really long complicated blocking synchronous separation.

[00:03:23] And then I call date on now again and say that is the end time, I can tell what's the difference between the two. And I can find how many seconds or whatever milliseconds it took for this thing to run. So that can be useful. But we also have a fun little built-in timer on the console object.

[00:03:46] Have folks used console.time? This is a fun one that it's not 100% reliable, of course, but for general purpose, none of this stuff is. Don't trust JavaScript when it comes to time. But, [LAUGH], this can be useful for a high-level idea of whether things are moving along as you expect.

[00:04:10] So I can start a new timer by calling console.time with the name of this timer. And that's just an arbitrary string that I choose. So in this case, I'll start one called stopwatched. And then I will runAround, in my mind, because I hate running. And then I can call .timelog on the console and pass in the same ID for this timer, which again, was what I chose, stopwatch.

[00:04:39] And it will tell me how many milliseconds that timer has been running. And I can then maybe even set another timer, like a lap timer. So for example, create a new console.time with a different ID. So I now have a different timer, which then I can do more stuff.

[00:04:58] And then I could maybe stop that timer totally by calling .timeend with my given ID that I'm interested in, in this case lap. And now the console will tell me, okay, the lap took this long and the timer is done. I'm not paying attention to lap anymore. That's we're done, we're past it.

[00:05:19] And then the stopwatch timer is still running at this point because I haven't called .timeend. So once I do that, we'll see, a much larger value for a timer that's been running for longer. So anyway, time, it's fun, especially when you can only count in milliseconds. So get used to a lot of divide by a thousand, or multiply by a thousand, or whatever.

[00:05:42] All righty, but console has some other fun tricks up its sleeve. So again, poke around to see what else you got on that console object in there. But there is another concept of timers that JavaScript and, well, I should say the browser has, which are timeouts. So try this out as we go in the console.

[00:06:09] If we log something, we expect to see it right away, right? But if we call the built-in function set timeout, and we pass in a callback function, in this case, we're doing the little anonymous fat arrow that we saw a minute ago. And we log something in that function, the second argument to set timeout is a delay, in guess what unit?

[00:06:38] In milliseconds, because everything's milliseconds in our world, because we're a browser. And we just see time stretch infinitely in front of us. Anyway, so basically the way set timeout works is I give it a function to run. I give it a delay after which I want it to try to run the function.

[00:06:59] We're gonna get back to our whole event loop situation. And what happens then, if I have the next line in my program, also just be a regular console log. So, if people try running this code, I'm just gonna copy it. What do you think? Will this last one print before or after this one second later?

[00:07:24]
>> Before.
>> Before, okay. Immediately, I don't know let's see what is immediate. Okay, so if we do this, we get it immediately. But if we run like these two right after one another, it does print immediately. And then about one second later this runs. And if you are capable in your mind of not having the SpongeBob name one second later in your head then you are a different brain than me because that's all I can can ever think of with these things.

[00:08:06] Many hours later, okay.
>> Excuse me.
>> Yes.
>> Where does the set timeout method live? What is that?
>> What is that? Shall we ask our friend?
>> Yeah.
>> Let's ask our best friend, every web dev's best friend, BFF, type in the thing that we're curious about.

[00:08:30] SetTimeout, global function, okay? Also available in web workers, outside of the scope of this course. So basically the setTimeout function is a global variable in the JavaScript client side runtime that gives us access to this browser API under the hood that the browser is managing of maintaining these timeouts.

[00:09:01] And so, we can read a lot more about timeouts in here. But again, this is one of those things that the browser is doing outside of JavaScript. And it has this notion of a timer. So, it sees the call, or JavaScript has this function on the stack that says, setTimeout with some callback function.

[00:09:26] And then the browser is, you wanted me to set a timeout. And then remember that that's the function I'm supposed to run that callback you just gave me. Okay, cool. Start the timer [SOUND]. It's been 1000 milliseconds or whatever. Now you should be ready to run that callback function.

[00:09:47] So the browser pushes that into the queue to be processed as quickly as possible, and this is why I keep saying it runs about a second later. It runs about immediately. Because again, there could be all kinds of other stuff happening. So really, when we're setting a timeout, and using similar API's which we'll see in a second, the delay is not precise.

[00:10:17] The delay is essentially a minimum. It's telling the browser, wait 1000 seconds or milliseconds and then schedule this function to be run. So put this callback function into the queue in a little message to JavaScript. And then only once the call stack is empty and that message is the front of the queue is that callback actually gonna get run.

[00:10:44] So it might be 2,000 milliseconds later. If somebody else was doing something else that blocked the call stack for a second, one whole second. So this is why we have very fuzzy notions of when things are happening, because the browser's doing all kinds of other stuff. What do we think we're the most important person in the browser's life?

[00:11:08] It doesn't have anything else better to do than just listen for our commands and execute them immediately? Whoa, browser. All right, but it's kind of fair, there's other things happening. So this is why be careful with timeouts. Don't trust them as an exact time and same with console.time and all this stuff.

[00:11:27] Nothing in JavaScript, [LAUGH] time-wise, is certain really. Although they're working on it. That standards body that I mentioned is working on a new alternative to date.now. So hopefully, one day, we'll have easier time as web developers. But anyway, for now, when we set timeouts, it's essentially a minimum, minimum delay.

[00:11:49] Just keep that in mind. We can also cancel timeouts. Sometimes got a rocket launch planned as one does these days. Cuz that's what JavaScript is for, right? Launching rockets. And let's say we have a countdown timeout. And this bears mentioning, sometimes it's useful to keep the return value of the set timeout function.

[00:12:18] And if we look at what that value is, if we log this countdown variable we've stored it in, it's some number. And it'll depend on how many other timers are going, whatever. But essentially, each running JavaScript process will give it an ID that can't be confused for any other timer.

[00:12:39] And we can use that ID to then clear or cancel the timeout if we need to. So if somebody smashes that abort button, for example, then we want to clear this time out and not have liftoff. So this is also kind of mirrored in a very similar API called intervals.

[00:13:07] So similar to timeout, where we're essentially saying, okay, wait this long and then try to run this function. With an interval, we're saying, wait this long and then try to run this function, and then wait that long again, and then try to run it again, and then wait that long again and try to run it again forever.

[00:13:24] Or until we run clear interval on the ID of the timeout we want to run. Now, be careful with these things. If you're setting an interval to do some very long or expensive or, yeah, I don't know, operation, and you're doing it every second, you might not be having a good time.

[00:13:48] But sometimes that is exactly what you want. Yes, and so back to our concept again, just to review that terminology or jargon, cuz let's keep in mind that these are all just arbitrary words that we made up to refer to these things. However, in the community, you will see words thrown around like blocking code, synchronous, asynchronous, non-blocking, yada, yada.

[00:14:13] So essentially, as a recap, if there weren't this whole process of the event loop being able to queue up things into JavaScript. Then JavaScript would basically have to block its execution until the current thing was done. And we wouldn't be able to do anything else with the browser if we were running a timeout, let's say.

[00:14:35] Or we wouldn't have a timeout because that's a browser thing. But if we were doing a very long complex task. So the event loop helps us avoid blocking the the browser's interactivity and being able to respond to other stuff that's going on. But we've all had the experience probably in our lives of some page that is indeed freezing up our whole browser.

[00:15:02] We can't do anything and so our goal forever, and to today, and in the future, is to not do that, and to give users a responsive experience by managing time consciously. So this is just the beginning of what could be said about this, but TLDR, a blocking code, less good.

[00:15:25] Non-blocking code, and that's where our async friends come in, excellent. Drake approves. So you know it's good.