Running JavaScript code without blocking the main thread

While studying JavaScript and JSON, I encountered some issues. I have a script that functions with JSON data, but the performance of my code is not optimal. The code only works when I debug it step by step using tools like Firebug which leads me to conclude that the execution time (especially the part related to creating the table) is too long, causing the browser to halt.

Below is the problematic section of the code:


// Javascript code block where JSON data is processed

The main concern is that the code responsible for generating the table does not wait for the JSON processing code to finish executing. How can I address this issue? I would prefer a simple solution without utilizing jQuery or callbacks since I am still a beginner in programming

Answer №1

To make it function properly, you need to rearrange some code. Initially, break it down into functions for easier handling. The process begins by loading the arrayEntita first. Once that is complete, the other two arrays are filled. Finally, when all arrays are populated, the table is constructed.

 var arrayCarte = [];
 var arrayEntita = [];
 var arraycardbyuser = [];
 function displayArrayCards() {
    var richiestaEntity = new XMLHttpRequest();
        richiestaEntity.onreadystatechange = function () {
             if (richiestaEntity.readyState == 4) {
             var objectentityjson = {};
             objectentityjson = JSON.parse(richiestaEntity.responseText);

              arrayEntita = objectentityjson.cards;
              BuildArrayEntita();
            }
        }
        richiestaEntity.open("GET", "danielericerca.json", true);
        richiestaEntity.send(null);
    }

    // Rest of the JavaScript code remains the same
 

The condition `if (i + 1 == arrayEntita.length)` checks if all responses have been received before executing BuildTable(); otherwise, ensure that all responses are returned before calling the buildtable().

Answer №2

When making AJAX requests, it is important to remember that they are asynchronous processes. They can arrive at any time during execution and JavaScript does not wait for the server response before moving on to the next task. Although there is synchronous XHR available, it is generally not recommended as it goes against the core idea of AJAX.

To handle this asynchronous behavior, a common practice is to use a "callback" function. This function is executed at a later time, allowing you to specify when exactly you want it to run. For example, if you need to generate a table after receiving data:

function getData(callback){
    //Setting up AJAX request
    var request = new XMLHttpRequest();

    //Listening for state changes
    request.onreadystatechange = function() {

        //Checking if the request is complete and successful
        if (request.readyState === 4 && request.status === 200) {
        
            //Executing the callback function with the received data
            callback.call(this, request.responseText);
        }
    }
    request.open("GET", "data.json"); //defaults to asynchronous (true)
    request.send();
}

function displayTable() {

    //Passing a function to getData to be executed upon data reception
    getData(function(data){

        //Code to generate the table using the received data
        //"data" variable here holds the JSON response
        
    });
}

Answer №3

After making the ajax call, it is important to encapsulate all subsequent code within the readystatechange function to ensure proper sequential execution.

Note: The explanation by @Dappergoat offers a clearer insight into this concept.

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

The time limit for execution has been surpassed during long polling operation

Currently, I am attempting to retrieve the most recent messages from the MySQL table using long-polling methods. If no new messages are received, I implement the sleep() function for a 10-second pause. In the event that no new messages arrive within a 10 ...

Having trouble initiating an AJAX call in Django and returning values to my form

Seeking assistance to run an AJAX call for a quick calculation in my django view and display the result within a span tag on my HTML page. New to Javascript, struggling with triggering my AJAX call. Below is my HTML and JS code: <input type="text" nam ...

Encountering a problem with server-side jQuery autocomplete

I attempted to utilize a customized service I created in order to make this jquery autocomplete example work, but unfortunately it's not functioning properly. Here is the code snippet: $( "#city" ).autocomplete({ source: function( request, res ...

Transform stereo sound to mono using JavaScript

Recently, I encountered an audio file in stereo with a .raw extension that needs to be converted into mono using Node. Despite my efforts, I haven't been successful in finding examples or libraries outlining the process. Any assistance on this matter ...

What should the AJAX file in TagManager jQuery look like?

I'm currently utilizing Tagsmanager with JQuery, which can be found at There is a feature that allows tags to be pushed via Ajax: jQuery(".tm-input").tagsManager({ AjaxPush: '/ajax/countries/push', AjaxPushAllTags: true, ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants & ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...

Creating a Like button using react.js

How can I make only the selected button change, instead of all at the same time when clicked? I have implemented a function that includes a Boolean state and toggles it const [like, setLike] = useState(false); const handleLike=()=> { setLike(! ...

The Angular.copy() function selectively copies properties and does not duplicate everything

Exploring a function within a service: $scope.addPeriod = function(newPeriod) { if(newPeriod.from !== '' && newPeriod.until !== '') { var index = $scope.newPeriods.indexOf(newPeriod); ...

Attempting to establish a connection with MongoDB through Realm

Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project. Here is the link to my project structure on CodeSandbox The folder structure includes: src ...

Set the value of one email input to another email input in AngularJS

I'm having trouble trying to link an email input field to another in angularjs without success. Here is what I have attempted so far: <div class="row-fluid"> <div class="control-group span12"> <label for="email">Email</labe ...

Encountering an issue while trying to modify a nested datatable within an editable datatable (Possibly an Ajax Error)

I'm trying to enable editing for a nested data table (expanded through row expansion) that is inside another editable datatable. The issue seems to be related to the ajax rowEdit event. Everything works fine when I have only one editable datatable, bu ...

Trigger an action when the input text is changed, specifically when the input is populated from a different source

Is there a way to trigger an action on an input when the text is changed from another input, like a datepicker? I attempted to trigger the action when I click the date on the datepicker, but it does not seem to be working. Any suggestions? See below for my ...

Deactivating Timeout Requests in Koa Server

I keep encountering a connection reset error. I strongly believe it's stemming from a lengthy REST request, causing it to timeout. { [Error: socket hang up] code: 'ECONNRESET' } Is there a method to deactivate request timeouts within Koa, ...

Issue: $controller:ctrlreg The controller named 'HeaderCntrl' has not been properly registered

I am encountering an error while working on my AngularJS program. I have defined the controller in a separate file but it keeps saying that the controller is not registered. Can someone please help me understand why this issue is happening? <html n ...

Creating a new image by converting canvas to an image and displaying it in a separate window with Ruby on Rails and

I'm having some trouble with this issue and would really appreciate your help. My goal is to convert a canvas into an image using toDataURL when a link, button, or image is clicked. Once the image is generated, I want it to open in a new window. Can ...

Exploring the Functionality of Using Multiple Middlewares in Vue.js 3

For my web app project using vue.js 3 and vue-router, I followed a helpful tutorial on implementing middleware pipelines. The tutorial can be found at: https://blog.logrocket.com/vue-middleware-pipelines/. This tutorial demonstrated creating middleware to ...

What is the best way to add a dropdown menu in front of a button?

I have a div containing a dropdown list of items and I want the user to be able to add more dropdown lists by clicking a button. Although I managed to do this, the issue I'm encountering is that the new list gets added after the button instead of ben ...

Transfer the value of a JavaScript variable to a PHP variable

var javascript_data = $("#ctl00").text(); <?php $php_variable = ?> document.write(javascript_data); <? ; ?> Is there a way to transfer the javascript_data into the php_variable? I'm encountering an issue with this code. Any suggestions? ...

Adjust the background of the input range style prior to the thumb icon

Is there a way to style the bar before the thumb with a different color on a range input? I have been searching for a solution without much success. This is the desired look: Unfortunately, Chrome no longer supports input[type='range']::-webkit- ...