1

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.