2

Consider this code running on the chrome console:

function main(){
  setTimeout(()=>console.log('Hello World!'), 5000);
};

main();

As per my understanding:

  1. The V8 engine will push main() into the call stack.
  2. The setTimeout() web API binding will be called by the engine, which in turn will trigger some native code outside of the main javascript thread.
  3. main() will be popped off the stack
  4. Once the 5 seconds has elapsed, the event loop will retrieve the callback from the callback queue and add it onto the call stack for execution.

My question (which I think is a very minute detail, but has been bugging me for awhile) at which point and by whom is the callback pushed onto the callback queue?

6
  • 4
    By the "some native code" you mentioned. For setTimeout specifically, it probably registers a timer with the OS and does get called back asynchronously itself when the timeout expires. It's not "the event loop" that pushes the callback, it's this native code. The event loop sits on the other end of the event queue, fetching events and executing code.
    – Bergi
    Dec 15, 2019 at 14:41
  • @Bergi If the callback is not handled by the engines, but by some external not engine related native code, then the external code somehow has to hook into the event loop again, because it cannot call the callback anytime. So I would say the idea that it is done as in 4. is not completely wrong. It, in theory, could be solved that way.
    – t.niese
    Dec 15, 2019 at 15:10
  • Just to clarify, I did not mean the event loop pushes the callback to the callback queue. 4. is about the event loop retrieving the callback that already got added to the queue. Dec 15, 2019 at 15:24
  • Exactly how this works depends on the base operating system, to a significant extent.
    – Pointy
    Dec 15, 2019 at 15:55
  • @fsociety OK, thanks for the clarification. But no, the event loop doesn't wait 5 seconds itself to retrieve a 5-second-old callback. The event loop always tries to retrieve events (and their associated callbacks) as fast and as soon as possible from the event queue. It's the native code that pushes the event to the queue after 5 seconds.
    – Bergi
    Dec 15, 2019 at 17:59

2 Answers 2

2

You can think of the event loop as this piece of pseudo-code at the core of the JavaScript engine:

while (true) {
  while (queue.length === 0) {
    sleep();  // Native way to let the current process sleep.
  }
  callback = queue.pop_first();
  callback();
}

And then the engine exposes a public function to its embedder:

function ScheduleCallback(callback) {
  queue.push_last(callback);
}

I'm obviously glossing over a bunch of details here (synchronization of queue access, waking up when something gets queued, graceful termination, prioritization of callbacks, ...), but that's the general gist of it.

To implement setTimeout, an embedder would use some other primitive that provides a waiting function (e.g. it could spin up a thread and put that thread to sleep for the desired time, or it could rely on a function similar to setTimeout provided by the operating system, i.e. some way to trigger a callback after a specified amount of time), and then call the function mentioned above. In pseudo-code:

engine.global.setTimeout = function(callback, delay) {
  OS.kernel.setTimeout(delay, () => {
    engine.ScheduleCallback(callback);
  });
}

This also explains why timeouts are not guaranteed to be precise: firstly, the operating system's timer primitive might have its own granularity constraints and/or might simply be busy; secondly the best an embedder can do is to schedule the callback after the specified time, but if your event loop is currently busy executing something else, then the scheduled callback will have to wait in the queue for its turn.

Side note: "pushing a function onto the call stack" is exactly the same as calling it; "popping it off the call stack" is exactly the same as having it return. The line "callback();" in the first snippet above does both. It's that simple!

3
  • Thank you for the detailed response! Correct me if I am wrong but since the callback queue is not implemented within the engine, how would the engine expose the ScheduleCallback function? Does the host environment provide a reference of the callback queue to the engine during initialization? Dec 16, 2019 at 1:45
  • Also, is the event loop implemented within the engine? I assumed it was a browser implementation Dec 16, 2019 at 1:50
  • 1
    V8 does have its own event loop and callback queue, which embedders can override if they need more functionality or control. Where exactly you draw the line between "the engine" and "the... uh... other thing that sort of constitutes part of the engine?" is (1) blurry and (2) an implementation detail that doesn't really matter in practice. I don't know how other implementations do it.
    – jmrk
    Dec 16, 2019 at 9:55
-1

As JavaScript is not multithreaded, a callback can't be called at any time or run in parallel to other code of the same "context".

As of that a callback function that is passed to some external code can't be called at any time by that external code, that call has to be initiated by the engine. To give the code execution some predict/reliable execution order, the engine uses the even loop for that.

How this is handled depends on the engine, the engine could tell the external code to check if there are callbacks to be called, and ask to call them. But that might result in undesirable groupings of callbacks. Or that external code could pass those callbacks that should be called back to the engine which stores them in a queue.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.