Is a single thread in nodejs and web browser same?

Viewed 233

The concept of single-thread and event-loop and callback in web browser is same with that of node.js ??

And if so, is it because v8 use that concept in doing work(both chrome and node.js use v8)?

Was v8 designed like that?

1 Answers

The specified behaviour of JS in ECMA-262 defines JS evaluation in terms of an "Agent" which is essentially an abstracted term for a thread. The JS engines of all major browsers follow this specification, and obviously Node.js uses the same engine as Chromium.

The execution context stack, which (in simplified terms) handles function calls, is scoped to agents, so you can't really work with JS in a multi-threaded environment.

This is why Web Workers cannot pass objects around, and instead use structured clones.

The concept of the event loop is also defined in the ECMA-262, with the combined behaviour of RunJobs() and Jobs and Job Queues. Job queues are also scoped to agents, so they cannot handle multi-threaded environments.

Promises are currently the only thing defined in ECMA-262 that use the job queue (Promise handlers always run in a new tick), but Node.js and browsers make heavy use of the event loop for IO.

Related