Understanding JavaScript call stack and Event Listener.

Rahul Roy
2 min readJun 26, 2018

--

JavaScript is a single threaded language unlike most to the popular programming language like Python. This means only one task is run by JavaScript at a time. JavaScript is the integral part of web today and all of the client side scripting relies on JavaScript.

The performance of web pages and time they take to render rely masively on java script. Writing elegant and browser compatible javaScript becomes esential for you webApp performance. How does javaScript maintains a call stack. Assume a code snippet.

function print5(){
for(let i=0;i<5;i++){
console.log(i);
if(i==3)
print2();
}
}
function print2(){
for(let j=0;j<2;j++){
console.log(j+" 2nd");
}
}
print5();

The above code snippet will result in a output of

0
1
2
3
0 2nd
1 2nd
4

The call stack for the above code snippet can be explained by this simple drawing.

JavaScript function are stored in the call stack but when a event listener with a function is encountered the function reference is stored in the browser memory and is evoked only when the event Listener is triggered. There is one thing to remember JavaScript runs on the principle of complete one task and then take up another do not stop the running process. Assume you have a event listener tied up to a element. Now when the event listener is triggered the function pertaining to it is called from browser memory not the call stack. Now assume the call stack is busy processing other function. JavaScript will wait until the running function is complete and then run the click event function.

var clickme = document.getElemntById('clickButton');
clickme.addEventListener('click' function(){
console.log("click me was clicked");
});

Now the user clicks the button but JavaScript was busy processing other function the user will experience a delay in response.

The Event function are not stored in call stack but browser memory not run until event triggered.

This delay can lead to bad user experience and must be looked into while writing client side script. The whole process is explained diagrammatically below.

User experiences a delay.

To know how to prevent this follow my blog. Leave a clap if the article was useful to you.

--

--