Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where do the browser web api's run in Javascript?

where do the browser web api's run in Javascript like setTimeout ?

Do they run in some other environment or they take the help of javascript single thread ?

like image 333
Piyush Biswal Avatar asked Mar 13 '18 19:03

Piyush Biswal


1 Answers

They run outside of the JavaScript runtime. Those "Web API's" are executed within the browser's Web API execution space.

setTimeout() for example, is a method of the window object (it can also be invoked as window.setTimeout()). window is not at all part of JavaScript (it's a browser object) and anything you ask the window to do for you is handled outside of the JavaScript runtime and by the browser's other capabilities. The request for the Web API call originates from within the JavaScript environment, but the execution of the API call actually runs outside of it.

This is the very reason that we can have asynchronous behavior in web applications. While the JavaScript runtime (which is a synchronous environment that can only do one thing at a time) is doing its one thing, the browser can be doing something else.

setTimeout(), alert(), navigator.geolocation, XMLHttpRequest are all examples of Web APIs that run outside of the JS engine.

Here are some other Web API's and here is a great video that explains this in the context of timers specifically.

like image 168
Scott Marcus Avatar answered Sep 23 '22 00:09

Scott Marcus