// Concurrency in JavaScript
Javascript is a programming language with a peculiar twist. It's event driven model means that nothing blocks and everything runs concurrently. This is not to be confused with the type of concurrency as running in parallel on multiple cores. Javascript is single threaded so each program runs core on one core.
Every line of code executes without waiting for anything to return. This sounds weird but it's true. If you want to have any type of sequential ordering you can use events, callbacks, or as of late promises. Let's see an example:
function delayedLog(index, delay){
setTimeout(function(){
console.log("Logging from function call #"+index)
}, delay)
}
delayedLog(1, 2000)
delayedLog(2, 1000)Now you might be wondering what setTimeout is doing and it's basically saying Run this function after this much time. Javascript is a Higher-order programming language which means you can pass functions as arguments. The first delayedLog will print to stdout after 2 seconds. The second one will print after 1 second. What you might expect to see is:
// ...wait for 2 seconds
Logging from function call #1
// ...wait for 1 second
Logging from function call #2
But that is not the case. Instead both will be fired at the same time one after the other and the output would instead be like this:
// ...wait for 1 second
Logging from function call #2
// ...wait for 2 seconds
Logging from function call #1