Playing with JavaScript: setTimeout()

Anjali
Anjali
Jan 21 · 5 min read

setTimeout() method as the name suggests calls a function after the specified time.

Or does it?

But before anything else, syntax. Below is the syntax of setTimeout() which is evaluating the function and logs out ‘Hello!’ after 3 seconds(3000 milliseconds).

Image for post
Image for post
Syntax of setTimeout()

Now, let’s run a simple code and see how should setTimeout() work

Input:

Image for post
Image for post
Input

Output: As evident the above code logs out ‘Hey!’ then comes ‘Adios’ and once 3 seconds have passed it logs out ‘Let’s play with JavaScript’

Image for post
Image for post

Easy, right? Right. Now let’s take another example.

Input: This time instead of 3 seconds, we’ll set it to a delay of 0 seconds.

Image for post
Image for post

Output: Technically, it should print things in the order, ‘Hey!’, ‘Let’s play with JavaScript’ and lastly ‘Adios’. But that’s not the case. Instead it logs these out in this order as given below

Image for post
Image for post

This is because setTimeout() is non-blocking.

Before explaining what that is, let’s look at another example. In the example below, I have used a while loop to delay ‘Adios’ from being logged by 5 seconds. Whereas setTimeout() has a timer for 3 seconds.

So should the browser log out ‘Lets play with JavaScript.’ before ‘Adios’? Let’s find out.

Input:

Image for post
Image for post

The answer to the above question: In a parallel ideal universe may be it should log out ‘Adios’ before ‘Lets play with JavaScript’ but here that does not happen. Instead this does

Output:

Image for post
Image for post

So, what happened? Why did it log out ‘Adios’ playing with JavaScript? Why wouldn’t setTimeout() play a fair game?

Coming back to setTimeout(). Weird, isn’t it? But only till we don’t know what goes into the backend of all this.

So, how the browser works?

What’s the concurrency model?

Why does setTimeout() behave like a brat?

Why do I always go off track and all that jazz?(Maybe not this one)

As mentioned before once, setTimeout() is non-blocking. It will execute only after all the statements outside it it have been executed as opposed to blocking code that blocks the further execution until that operation is finished.

Read along, this will all make sense in a minute.

Concurrency Model: We have heard one time or other that JavaScript is a single-threaded language. It means that it has one call stack and it will execute only one thing at a time till its completion.

So, JavaScript has a concurrency model based on an event loop which waits synchronously for a message if there is not one already present or waiting to be executed.

Call Stack: A call stack handles the execution context. As the name implies, it works on the LIFO(last in first out) principle. Any statement(blocking and non-blocking) or a function that is to be executed is pushed on top of the call stack and once it completes, it gets popped off from it.

Callback Queue: I’ll explain callback queue via what might be the assumption.

Assumption(that one might have): setTimeout() waits for the specified time and then calls the function for execution.

Reality: setTimeout() registers the callback function and waits for the specified time(3000 milliseconds in this case). Then it is moved to the callback queue and waits for the call stack to be empty. The moment it gets empty and there is no other function waiting, the callback function moves from the callback queue to the call stack and it gets executed.

Here’s a pictorial representation of the above explanation

Image for post
Image for post
Used Xd to make these

Now, let’s analyze the third example once again with the help of this diagram

Image for post
Image for post

Once the statement is executed, it gets removed from the call stack.

Image for post
Image for post
Image for post
Image for post

And that’s how despite having setTimeout() being specified to execute after 0 milliseconds, the function gets executed only after all the blocking statements have already been executed.

Say there are million lines of code after a setTimeout()(Look at this example again where I have used a while loop to delay the process by 5 seconds on purpose).

Image for post
Image for post

The setTimeout() function sure has 3000 milliseconds specified in the argument but now we know that it will not get executed after 3 seconds. First all the blocking statements will get completed and then it will get executed a little later after 5000 milliseconds. That’s why ‘Lets play with JavaScript.’ gets logged out after ‘Adios’.

In other words, the time specified in the setTimeout() argument is not the time for the function execution but actually the time after which it moves to the callback queue.

See, told you it will all make sense in a minute(Okay, may be more than a minute). I hope this helped you understanding this concept a bit better.

One can always learn more and these are my interpretations of these concepts. If you find that something was not explained in a correct way, do tell me, it will help me improve my understanding. I’ll take all constructive feedback(be it for the concepts or for the article) positively.

If you want to delve further into these, do try it yourself and read more about it. Here are the links of a few resources that helped me:

MDN Web Docs, Understanding setTimeout(), W3Schools, Akshay Saini

I read from various resources and I have added a few above as it’s not possible to mention all the links. However, I will add all that I remember even in the future.

If you liked this, do share it.

And you can connect with me on Twitter here and/or LinkedIn here.

Thanks for reading!

Anjali

Written by

Anjali

Don't play with Jazbaat, play with JavaScript instead. It's actually fun. If you already follow me, please don't unfollow me because of this bio.

The Startup

Medium's largest active publication, followed by +775K people. Follow to join our community.

Anjali

Written by

Anjali

Don't play with Jazbaat, play with JavaScript instead. It's actually fun. If you already follow me, please don't unfollow me because of this bio.

The Startup

Medium's largest active publication, followed by +775K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store