Callbacks and Asynchronous code

JavaScript is a synchronous, single threaded programming language. This means that instructions can only run one after another, and not in parallel. Each instruction waits for the previous instruction to complete its execution.

snippet.js
console.log("step 1");
console.log("step 2");
console.log("step 3");
output
step 1
step 2
step 3

Asynchronous code execution allows to execution next instructions immediately and doesn't block the flow because of previous instructions.

snippet.js
console.log('Step 1');

// Set timeout for 3 seconds
setTimeout(() => console.log('Step 2'), 3000);

console.log('Step 3');
output
Step 1
Step 3
Step 2

Simple analogy for synchronous and asynchronous code

Synchronous Execution

My boss tells me to write code. I tell him: Fine. I get started and he's watching me like a vulture, standing behind me, off my shoulder. I'm like "Dude, why don't you go and do something while I finish this?"

He says: "No, I'm waiting right here until you finish." This is synchronous.

Asynchronous Execution

The boss tells me to do it, and rather than waiting right there for my work, the boss goes off and does other tasks. When I finish my job I simply report to my boss and say: "I'm done!" This is Asynchronous Execution.

References

Last updated