Playing with JavaScript: setTimeout()

Anjali
The Startup
Published in
5 min readJan 21, 2021

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).

Syntax of setTimeout()

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

Input:

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’

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.

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

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:

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:

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

Used Xd to make these

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

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

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).

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
The Startup

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.