WelcomeTo
WelcomeTo

Reputation: 20591

How JS determine when to call Callback function?

I am wondering how JavaScript callbacks work. I specifically can't understand how asynchronous XmlHttpRequest works. How can JS determine that server returned some value (in one thread), and when to call callback method? Is it build on timers?

Upvotes: 1

Views: 381

Answers (5)

jfriend00
jfriend00

Reputation: 707846

A very similar question was answered here in more detail.

The basic answer is that the underlying networking is happening at the OS level where there can be threads or some type of notifications when incoming networking packets arrive. When the result has completed, an event is added to the javascript event queue. When that event gets to the top of the event queue and javascript is ready to act on it, the proper javascript ajax event will be triggered which starts the chain of javascript that results in calling your callback.

There may some timers involved for timeouts, but timers are not used to know when the ajax response has arrived. That's based on the OS level networking support that the browser uses.

Upvotes: 2

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

The asynchronous nature of the XmlHttpRequest is provided at lower level than javascript (by the browser). The callback function is initiated by the browser signalling to the javascript engine that the request is complete.

Upvotes: 1

Evert
Evert

Reputation: 99717

Basically..

Whenever there's no javascript executing at the moment, events triggering from settimeout and responses to XmlHttpRequest are checked. They are indeed added to an event queue.

The interesting effect of this, is that as long as javascript is currently executing, events like these will never be triggered.

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120268

Remember, javascript runs in an environment. That environment is not single threaded. When an xhr returns the browser (the environment) notifies the javascript engine that the xhr returned, and it in turn will execute the callback. Also remember that even though the programming model of javascript for the user is single threaded, javascript itself does not have to be.

Upvotes: 1

Jordan
Jordan

Reputation: 2758

You wouldn't use timers since you couldn't tell when they should trigger.

I'd imagine it is using some sort of stack/queue [list or table] to keep track of calls and popping the response function off depending on the returned info telling you which request it was responding to.

Upvotes: 1

Related Questions