e11438
e11438

Reputation: 894

Understanding Single threaded Functionality of JavaScript

I have this code snippet for hide a paragraph and alert a message after that

$(document).ready(function(){
    $("p").hide("slow");
    alert("stop");    
});

This doesn't work as I wanted to work. It gives the alert before finish hiding the paragraph. I understand that it can be corrected by using a call back function.

My question is if JavaScript is single threaded why doesn't it wait until finish hiding the paragraph to alert the message? If it is single threaded shouldn't that JavaScript first finish the hiding process and then come to alerting part?

Can someone please explain it.

Upvotes: 1

Views: 47

Answers (2)

Nitin Garg
Nitin Garg

Reputation: 896

Javescript is a single threaded. Just to extend @Arun answer if you use javascript way of hiding the element you will see that it first Hide the element and then popup alert message i.e something like

$(document).ready(function(){

document.getElementById('paragraphElement').style.display='none';

alert("stop");    
});

Hope this helps you understand better.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Because the animated version of hide works with timers(asynchronous)... ie it will initiate a sequence of timer operations to update the css property.

The call to hide('slow') will initialize the timer, which will get invoked at regular intervals to update the css property like opacity, so once the timer is set up the rest of the statements after the call will get executed. Once the current execution stack is completed the calls to the timer will take place.

Upvotes: 6

Related Questions