1

I have a fundamental confusion in Node.js technology. Let me explain with this small example.

I have this piece of code

setTimeout(function (){ console.log('world'); }, 2000); console.log('hello'); 

When I start executing this code, it immedietely prints 'hello' and after 2 seconds it prints 'world'.

Now I just want to know that if node.js is said to be the single threaded framework, then in which context or where(thread/process) this setTimeout function gets executed since the only single thread is executing the remaining code (printing world).

In case of I/O calls like DB hit, node.js uses the Libeio which in turn use threads internally. So it is not single threaded at all.

Am I right??

Please suggest.

Thanks

1

2 Answers 2

2

Node.js does indeed use threads internally. When they say it's "single threaded" they mean that the javascript is run within only one of those internal threads.

This thread runs an event loop which can be summed up as this:

while true foreach events as event call event js callback endforeach endwhile 

your setTimeout function creates a timer in the event loop, triggering it to call your callback later.

Sign up to request clarification or add additional context in comments.

Comments

1

The timers are executed in the same thread, in the "javascript single thread": Understanding javascript timers.

The file system calls occur at a C/C++ level. Internally nodejs uses a pool of threads. The libuv library provides that functionality and therefore, asynchorous calls at a C/C++ level. Then, node.js exposes a public api to the "javascript single thread".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.