Javascript is, technically speaking, single threaded. But it does have concurrency, practically speaking. Or, from our human point of view, there are things that seem to "run at the same time". For example, two separate separate setIntervals
s (a way to get a code to be run in intervals after a certain time) "animating" two separate objects "at the same time". And while that's running, we can have a button that, when clicked, outputs text.
Example
This is a good explanation of what really happens, javascript runtime wise. From the article, it is something like:
while(queue.waitForMessage()){
queue.processNextMessage();
}
So let's say the initial block of code will be the first message. it sets up the onLoad
and maybe some setIntervals
. This will create new messages. When the page finally loads, it will be passed to the queue to be run. When a timeout, times out, it will also be sent to the queue to be run. But a message must finish before the next message will be run. So it looks like as if things are happening at the same time but, in actuality it's just short messages being run in a queue.
So the classic example will be, Example
setTimeout(function(){
result.innerHTML+="1,";
},0); //wait time in ms
result.innerHTML+="2,";
setTimeout(function(){
result.innerHTML+="3,";
},0); //wait time in ms
result.innerHTML+="4,";
Which will output 2,4,1,3,
. So what happens is that the initial message will run, create two timeouts which will pass the functions as a message to the queue when the set time elapses (in this case, 0, which means it gets immediately sent to the queue.
It should be noted that the messages should be short. Perhaps it must. but that doesn't stop you from coding a really big for loop that traverses and processes huge 2D arrays from blocking your code (freezing everything) which, after a couple of seconds would lead to "This page is unresponsive" alert. Or in fact, as per the mozilla article, an alert()
actually blocks. So i'll modify the examples and add to see them stop execution.
Also. Specific to your code, jQuery adds to the confusion in that jQuery automagically queues the animations up. Compare this jquery code:
$("#test").animate({"left":100},2000)
$("#test").animate({"top":100},2000)
With this plain javscript code;
var x=10;
setInterval(function(){
x+=1
test.style.left=x+"px";
},20)
var y=10;
setInterval(function(){
y+=1;
test.style.top=y+"px"
},20)
Granted, it's not exactly the same piece of code, which would involve callbacks. But I think it illustrates my point that, .animate
has some magic queuing.
Actually, to close, it'll be good for you to look at promises pattern moving forward. which makes chaining these asynchronous events not be a crazy clusters of callbacks.