adjective:
1. Not Synchronous.
2. Not occurring at the same time.
In "synchronous" programming every line of code happens in order. Any operation that requires some time to pass will block until the operation finishes.
In a polite conversation, after the speaker makes a point they will wait for their partner in conversation to respond.
Synchronous: A Conversation
When you send an email you don't freeze your whole life to wait for that reply. You continue with your day day.
Asynchronous: An Email
Synchronous:
Asynchronous:
for(let i = 0; i < 10; i++) {
console.log(i);
}
console.log("done");
for(let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 0);
}
console.log("done");
Synchronous:
for(let i = 0; i < 10; i++) {
console.log(i);
}
console.log("done");
In this block of code, the line inside the loop behaves synchronously. Each console.log statement waits for the previous to complete before moving on.
Asynchronous:
for(let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
console.log("done");
In this block, the setTimeout introduces asynchronous behavior. Specifically, "done" prints first, followed by the 10 callbacks executing one second later.
The ability to wait without blocking can help us write more efficient programs by never wasting time.
If each setTimeout had to wait for the previous to complete in our code -- it would take 10 seconds instead of 1:
for(let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
console.log("done");
Lots of things take time to fetch that don't need to block -- like reading from the filesystem or AJAX requests.
User Input is asynchronous by definition; we never know when a user is going to click or hit enter.
The Message Queue is a place in memory where JavaScript keeps a list of "messages". Our code from before creates 10 such messages -- each associated with a callback
for(let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
console.log("done");
Anytime the current process finishes, The Event Loop requests the next item in The Message Queue.
for(let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
console.log("done");
while(queue.waitForMessage()){
queue.processNextMessage();
}
Processing the Next Message means putting the function associated with that message on top of The Stack, which will be empty at this point.
while(queue.waitForMessage()){
queue.processNextMessage();
}
function() {
console.log(i);
}
The message is removed from the queue when we start processing it.
while(queue.waitForMessage()){
queue.processNextMessage();
}
function() {
console.log(i);
}
After the message is processed, we re-enter The Event Loop.
while(queue.waitForMessage()){
queue.processNextMessage();
}
Completes, pops off stack
Repeat
while(queue.waitForMessage()){
queue.processNextMessage();
}
function() {
console.log(i);
}