How does the event loop works in javascript?

Hi,

I have the following code on the click of a button,

$("div").addClass("loading");
this.callSomeMethod();

what is happening is if I directly call this way loading icon doesn’t show up.

but if I call in the following way it does,

$("div").addClass("loading");
SetTimeout(function(){this.callSomeMethod()},100);

can someone please clarify me the reason why this is happening this way?

Because of the context. An event listener’s context is the element it is bound to, the context of setTimeout() is window.

That function wrapper is actually not necessary anyway; you could just write

setTimeout(this.callSomeMethod, 100)

Or if callSomeMethod() needs that this context as well:

setTimeout(this.callSomeMethod.bind(this), 100)

Since his code resides in the event listener, the problem is that he expects this to be something other than the DOM element.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.