1

I know what is and how to use callback in javascript. My question is how does the javascript engine e.g. V8, implement callback? the callback mechanism is used everywhere in async event handling, e.g. event callback, database query.

Is it in a while true loop? or some other form,e.g. using select.epoll()?

If there is a 10 thousand callbacks in a javascript app, will it slow the whole thing?

Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129
  • By "callback", do you specifically refer to asynchronous event handlers? – Bergi May 01 '19 at 18:35
  • 2
    You will want to look up "event loop". – Bergi May 01 '19 at 18:36
  • @Bergi yes, I updated the question to make it more clear. thanks! what event loop? Can you help me answer the question? thanks! – Nicolas S.Xu May 01 '19 at 18:41
  • If you don't know what an "event loop" is, then you should research that term to find the answer to your question. – Bergi May 01 '19 at 18:48
  • 1
    For details about node.js and the V8 engine, you'll wan to have a look at [these](https://stackoverflow.com/q/36491385/1048572) [threads](https://stackoverflow.com/q/50115031/1048572) and follow the links therein. – Bergi May 01 '19 at 18:51
  • The best way to learn about "event loop" is with [Philip Roberts video from JSConf](https://www.youtube.com/watch?v=8aGhZQkoFbQ) – Leibale Eidelman May 01 '19 at 18:52

1 Answers1

1

Essentially your javascript code is compiled down to a data structure called Function which can be called and are stored in a runtime function table.

V8 Doesn't necessarily manage the calling of the callbacks or manage a loop but instead ensures that all execution of its structures happen in the same thread and then relies on the underlying engine to manage work done in background threads and event looping and calling callbacks.

For example nodejs uses libuv for its underlying runtime functionality including the uv_loop_t to manage the actual event looping in the main thread.

As functions are called such as fs.readFile it will eventually dispatch into a libuv function which takes care to do the work in a background thread and then ultimately takes care to manage the threading involved with pushing that work back into the main event loop.

Essentially the main event loop is a for(;;) loop that reads these responses out of a queue and continues so long as there are background threads kept alive.

Browsers work in a very similar way but they each have their own implementation of the same concepts.

justin.m.chase
  • 13,061
  • 8
  • 52
  • 100
  • 1
    Minor correction: JavaScript functions are represented of instances of `JSFunction` (in `src/objects/js-objects.h`), and they are not stored in a table. "Runtime functions" are a different concept, they are a special part of V8's C++ code. – jmrk May 02 '19 at 09:08