r/learnjavascript • • May 01 '20

Async vs. Sync

Post image
413 Upvotes

81 comments sorted by

View all comments

1

u/liaguris May 01 '20

Wait a second here . I am confused . How is the right chart possible in a single threaded language like javascript?

2

u/[deleted] May 02 '20

If the overlapping bits are spent waiting for something, like hard drive, network, timeout, etc.

1

u/liaguris May 02 '20 edited May 02 '20

Ok I get it now.

For the network case maybe we have non-single thread-like behavior in the server who is processing the requests .

I think it is the same about hard drive also , where the computer can have multiple cpu cores.

I can imagine something like this for setTimeout out :

while (true) { 
	//microtasks 
	//.... 
	//macrotasks 
	for (let { timeout, cb, timeoutId } in obj) {
		if (--timeout === 0) {
			cb();
			delete obj[timeoutId];
		}
	}
	//animationFrame?
	//...
}

which is single thread behavior.

What is the y axis supposed to represent?That chart is really misleading.

The whole story about asynchronicity in javascript is doing stuff in a single thread after the whole synchronous code has executed . The asynchronous chunk are done one after the other and they never overlap their cpu usage (= single thread).

Correct if I am wrong but I think an exception might be workers where we can have multi-threaded (parallel?) behavior if the computer has many cpu cores.