Taking the setTimeout method as an example, how does JavaScript know that that specific method is asynchronous? How does it know that it has to push the method into the queue of the event loop ?
Can anyone throw some light on this ?
Thank you.
Taking the setTimeout method as an example, how does JavaScript know that that specific method is asynchronous? How does it know that it has to push the method into the queue of the event loop ?
Can anyone throw some light on this ?
Thank you.
var queue = [];
function add(callback) {
queue.push(callback);
}
How does JavaScript know that it has to push the
callback
function to thequeue
array?
It doesn't "know". It just executes the add
function.
It's not any different for setTimeout
- except that the function is not written by the JavaScript programmer, but exposed as part of the native API built into the browser. JavaScript does not know what it does, it just calls it.
First, understand that JavaScript runs within its own execution environments (a runtime). That runtime is just one application running within the host operating system and that OS is capable of muti-threading (asynchronous operations). The JavaScript runtime can be doing one thing while the OS does something else.
The JavaScript runtime processes all code synchrously. This is by design and written into the ECMAScript specification. So, there is nothing that the runtime has to figure out.
Most clients provide additional APIs (beyond what’s in the spec.) and those operations are often done asynchronously because they aren’t being done by the runtime - they are being done by the client. setTimeout() is an example of this. It’s not part of JavaScript. It’s part of the browser supplied window object and the timer is actually carried out by the browser.