what is the value of “this” inside javascript setTimeout?

Let’s start with the basics and understand how the setTimeout methods are executed in the browser. We will see the Call stack, Browser API and Message queue to understand the topic here. Basically every statement executed in Javascript are sent to Call stack to get executed one by one and in there if it encounters any statement which involves Browser API such as setTimeout/setInterval the statement will be forwarded to Browser API execution layer and once the browser completes the task like waiting for the specified time to complete it will forward the statement to the Message queue which are executed once the Call stack is empty.

Now let us go through an example to understand what we studied above

The output for this function is
1
5
2
4
3

The below image illustrates how the statements inside the function are executed.

If you understood or if you already knew this then well and good, now let’s move on to the sole purpose of this article.
To put it in simple words, the value of this i.e the context we are working will get changed inside the callback function like every other approach. If you have used Jquery then you would have faced this at least once, the value of this will be the object which contains the details of the DOM element on which we have invoked the method. To hold the value of parent context we assign it to a variable and access it inside the callback methods.
Like
var that = this;

The same is happened inside the callback methods of setTimeout. By executing the below function we will understand that the context will be changed when it comes to the callback.

The output for this function is
1
2
undefined

As we expected the value accessed from the parent context is undefined inside the callback function.

This was the old school approach of handling callbacks in javascript, From the time ES6 has come with many new features, solving these problems have become very easy.
we will be using one of the features of ES6 to overcome this problem, They are nothing but Arrow functions.
Please go through my article on Arrow functions to understand the basics so that we will be in same page when we work on the next example.

As you would have read Arrow functions does not have their own context/this, using them as callbacks will help us still access the parent context in javascript. See the below example to understand.

The output of this function is
1
2
3

Hope we learnt something new today.
Happy coding:)

Tagged as: , , ,