The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet:

request(..., function (error, response, body)  
    console.log('foo);  
});  
callAComputationallyIntensiveSynchronousFunctionThatTakesSixHoursToExecute();  
console.log('bar');  

'bar' will still come before 'foo' because Javascript always finishes the currently executing function first. An event will never interrupt a function.

I grasp the concept that synchronous functions take precedence over events, but what baffles me is why 'bar' would be displayed before 'foo'. My understanding leads me to believe that an async call should trigger, allowing for other lines of code to run until the response is prepared, subsequently executing the callback function and resuming the code execution accordingly.

In the example provided, it seems that despite the response being ready well in advance of the synchronous function completion, Javascript proceeds to execute the subsequent line of code. This begs the question - what is the rationale behind this behavior?

Answer №1

When it comes to JavaScript, every aspect revolves around functions. Whether synchronous or asynchronous, there is no clear line that distinguishes the two types of functions. It all comes down to how you invoke these functions, with "sync" and "async" serving as abstract concepts that aid in communication among programmers.

Understanding the inner workings of JavaScript:

In JavaScript, there exists a queue of functions waiting to be executed. Whenever a new "asynchronous function" is created, it joins this queue. This typically happens when utilizing methods like setTimeout(), making ajax calls, or responding to DOM events such as "onClick" triggered by the browser.

Once a specific function begins execution in JS, it continues running until completion without any interruptions. After the current function finishes, the runtime (browser) examines the queue, determines the next function to run, and proceeds with its execution before awaiting its completion.

Consider the example provided above— at present, the browser is executing the function responsible for printing "bar". This process cannot be halted midway through, leading to the immediate printing of "bar". Meanwhile, during this execution, a new asynchronous function is generated and added to the execution-queue. Upon "bar" being successfully printed, the runtime scans the queue, locates the "foo"-function, and executes it accordingly.

An inherent drawback of this system pertains to lengthy tasks. While a function is undergoing execution, the browser remains occupied, rendering updates or interactions impossible. In situations where a piece of code takes approximately 10 seconds to run, users are unable to interact with the website until the function concludes. This restriction arises due to the queuing of all user-induced events like mouse movements, clicks, or scrolling actions, which remain pending until the long-running task reaches completion.

Exploring Multithreading using JavaScript:

With HTML5, JavaScript has introduced the capability of leveraging multiple threads via technologies like web workers. Nonetheless, delving into this topic requires a separate discussion beyond the scope of the current context. It's essential to acknowledge the theoretical feasibility of multithreading with JavaScript thanks to recent advancements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQuery magic: Enhancing a div's visibility with animated mouseover effects

I'm trying to figure out how to animate a div on mouseover, specifically making it fade in/appear slowly. I believe I need to use the .animate function or something similar. $("#logo").mouseover(function() { $("#nav").css('visibility',&apos ...

Having trouble updating the route with the $location service, even after attempting to use $scope.apply

After trying to utilize the location service with no success, I am left wondering why my view isn't changing even after using either $scope.$apply() or $scope.apply. Prior to posting my question, I conducted thorough research on similar inquiries but ...

Exploring the capabilities of Three.js Projector and Ray components

Recently, I've been experimenting with the Projector and Ray classes for collision detection demos. My main focus has been on using the mouse to interact with objects by selecting or dragging them. While studying examples that utilize these classes, I ...

disappearing the link in a window.open popup

I have a situation where I am opening a window with the code window.open("mytest.aspx");. The issue arises when the user closes that pop-up window - I need to have the link on the parent page hidden. In essence, how can I hide the anchor link on the parent ...

Transform the features of a website into a sleek iOS application using Swift

Can I take an HTML website coded with JavaScript and integrate its functionality into my app using WebKit or another method? By using WebKit or WebViews, I can load an entire webpage into my app, automatically bringing along its functionality. However, i ...

Tips for positioning the cursor at the beginning of text and shifting the focus to the start while utilizing the MaterialUI Input component

I have scoured various online forums for a solution to this issue, but none of the suggestions seem to work. Although I managed to position the cursor at the beginning of the text, it did not shift the focus accordingly. Here is the code snippet for the co ...

What is the best way to display a number or integer using axios?

Need help retrieving the integer from the response obtained through an axios get request Here is what I see in the console log: https://i.stack.imgur.com/ztmf0.png setDappList([response.data.stats]); <div>{setDappList.total}</div> Unfortuna ...

Emphasize SELENIDE rows

My goal is to achieve the following: @Test public void tableTest() { getDriver().get(BASE_URL + "tabulka.php"); List<WebElement> rows = getDriver().findElements(By.xpath("//table//tbody//tr")); for (We ...

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

Tips on invoking a JSP and Servlet from JavaScript by passing in a parameter

Check out the code below for calling JavaScript functions: <td><input type="button" name="edit" value="Edit" onclick="editRecord(<%=rs.getString(1)%>);" ></td> <td><input type="button" name="delete" value="Delete" onclic ...

Building a Wordpress website with AJAX functionality using only raw Javascript and no reliance on Jquery

So, I have a custom script named related-posts.php, and I want to insert it into posts only when the user scrolls. In addition, I have an enqueued script file in WordPress that loads in the footer, where I have written AJAX code like this: var xmlhttp = ...

Executing the countdown function within the catch/error block of $http.post does not work as expected in Vue.js

I encountered an issue with a simple code snippet that involves calling a countdown timer within the catch function of $http.post. this.$http.post('/api/task/post', updatedTask ,function(data){ alert('success!') }).catch( ...

Revolving mechanism within React.js

I am currently developing a lottery application using React.js that features a spinning wheel in SVG format. Users can spin the wheel and it smoothly stops at a random position generated by my application. https://i.stack.imgur.com/I7oFb.png To use the w ...

Ways to confine the tabindex within a specific div container

I am currently working on identifying examples of bad accessibility practices. Specifically, I am focusing on issues related to Keyboard Focus. The first example I have encountered is the lack of visibility when trying to navigate through a set of buttons. ...

JavaScript isn't functioning properly after UserControl is loaded via Ajax

Thank you, Stilgar for helping me solve my issue. I created a javascript file and placed all my code in it. After adding this file to the UserControl and retrieving the UserControl's html, I used $("#DivID").html(UserControlHTML). Now everything is wo ...

Guidelines for choosing AngularJS checkboxes to exclusively choose distinct matching items

Need help with selecting common items using Angular checkboxes. Below is the mock UI-Table: Order Id | Delivery Mode | Select 1 | Speed | ::checkbox:: 2 | Normal | ::checkbox:: 3 | Contractor | ::che ...

Trouble with linking an external JavaScript file in HTML document

I'm having some trouble including an external JavaScript file in my HTML. I followed the steps but the pie chart is not showing up as expected. Can someone please take a look and let me know if I missed anything? Here's the link to where I got th ...

Toggle visibility of a div with bootstrap checkbox - enforce input requirements only if checkbox is marked

Lately, I've been facing a strange issue with using a checkbox that collapses a hidden div by utilizing bootstrap. When I include the attribute data-toggle="collapse" in the checkbox input section, the div collapses but it mandates every single one o ...

Navigation bar failing to show all content on Safari web browser

When navigating to this website, http://www.togethermutualinsurance.co.uk, using any browser except for Safari on Windows, the menu displays correctly. However, in Safari, the title of the menus and submenus with images does not display properly. Despite ...

The efficiency of Testing Library findBy* queries is optimized when utilized alongside async/await functionality

After reviewing the documentation, it was noted that queries made using findBy return a Promise. Interestingly, utilizing these queries with Promise.prototype.catch() seems ineffective in comparison to pairing them with async/await + try...catch. An insta ...