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?

6
  • By "callback", do you specifically refer to asynchronous event handlers? Commented May 1, 2019 at 18:35
  • 2
    You will want to look up "event loop". Commented May 1, 2019 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! Commented May 1, 2019 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. Commented May 1, 2019 at 18:48
  • 1
    For details about node.js and the V8 engine, you'll wan to have a look at these threads and follow the links therein. Commented May 1, 2019 at 18:51

1 Answer 1

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.

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.