TIL what Single Threaded & Non-blocking means in JS
POSTED ON:
TAGS: javascript advanced
Javascript is a single-threaded language. This means it has one call stack and one memory heap. As expected, it executes code in order and must finish executing a piece code before moving onto the next. So if we print from 1to 5 it will execute every line one by one and can’t execute all prints at a single time.
Let's use a real example:
console.log("started");
const url = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
fetch(url).then(() => {
console.log("data fetched");
// return response.json();
})
console.log("ended");
In Javascript, the result will be:
started
ended
data fetched
What actually happens is for async calls, they get added to the queue and is revisited AFTER the stack is cleared (after the code goes from top to bottom).
In blocking languages, like C, or PHP, it will instead be:
started
(going out to fetch the data)
data fetched
ended
via What does Single Threaded & Non-Blocking mean in JavaScript?
Related TILs
Tagged: javascript