The Javascript function will keep on executing long after it has been invoked

I am currently facing an issue with calling a JavaScript function within an AJAX call. The progress function below is supposed to be executed every time the for loop runs. However, the problem is that although progress is being run as many times as the for loop iterates, it only executes after the rest of the code has completed.

For clarity, I will only share the essential parts of the code. All variables are properly defined and retData contains a list of objects that are accessed correctly. My main focus now is on ensuring that progress functions during the execution of the for loop and not after it.

function getAllProcess(){
    $.get(processUrl, function(retData){        
        if (navigator.appVersion.indexOf("Win")!=-1){
            windowsFillProcessTable(retData);
        }else{
            linuxFillProcessTable(retData);
        }//end else
        $('#divForProcessTable table tbody').append(processHtml);       
    });//end get
}

function windowsFillProcessTable(retData){
    $('#divForProcessTable table tbody #processTableHeaders').append("<th>Session Name</th><th>Session #</th>");
    lengthOfList = retData.list.length;
    step = 100/lengthOfList;

    if (retData.list.length > 0){
        for (var i = 0; i < retData.list.length; i++){      
            numberOfLoaded++;
            progress(step * numberOfLoaded, $('#progressBar')); 

            processHtml += '<tr><td><input type="checkbox" value="' + retData.list[i].pid + '">' + retData.list[i].pid + '</td><td>' + retData.list[i].name + '</td><td>' + retData.list[i].virtualMemorySize + '</td><td>' + 
            retData.list[i].user + '</td><td>' + retData.list[i].cpuTime + '</td><td>' + retData.list[i].status + '</td><td>' + retData.list[i].sessionName + '</td>' +
            '<td>' + retData.list[i].sessionNumber + '</td></tr>';                          
        }//end for
    }//end if for length
    else{
        processHtml = '<tr><td colspan="15">There are no processes matching that expression</td></tr>';
    }
}

//Loading bar action
function progress(percent, $element) {
    var d = new Date();
    console.log(new Date());
    var progressBarWidth = percent * $element.width() / 100;
    $element.find('div').animate({ width: progressBarWidth }, 500).html(percent + "%&nbsp;");
}

Answer №1

It seems like the real issue you're encountering is not that progress only runs once the for loop completes, but rather that the div where you want to show this progress is only updated once the windowsFillProcessTable function finishes its execution. Due to JavaScript's single-threaded nature (at least for now), the execution of windowsFillProcessTable blocks all other processes, including DOM updates.

You'll need to explore alternative methods to update your progress bar. Take a look at this resource or this one for potential solutions.

Answer №2

After exploring the potential of utilizing workers, I found that it could be a solution, although the correct implementation remained elusive to me. Despite this, I am setting this as my chosen answer since no one else has provided insight on how to leverage a worker thread for asynchronous DOM updates. It's worth noting that workers do not grant direct access to the DOM. Here are a few restrictions associated with workers: - The DOM (due to lack of thread safety) - The window object - The document object - The parent object

I came across this information at: http://www.html5rocks.com/en/tutorials/workers/basics/

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

Ways to locate an ID inside a specific selector?

After coming across this solution here, I've been using jQuery to clone a group of elements and update their ids in a .find .each loop to ensure they remain unique. Here's how it works: newElement.find(':input').each(function() { ...

The parameter provided should be in the form of a 12-byte string

Hey there, I am facing an issue while trying to delete an entry in my database. Despite attempting JSON.parse on the req.body and rearranging the routes in my routes file, I still can't seem to get it to work. Here is my controller: async function re ...

I encountered an AJAX error while working on my project

Encountering an error with my login_process.php when using ajax, preventing me from progressing. All files are stored in a single folder. Upon running the HTML log-in page, the error becomes visible. Below is the code snippet, quite straightforward. Previo ...

A method in JavaScript to fetch a single variable using the GET request

Although I am new to writing JavaScript, I am currently working on an iOS application that will make use of JavaScriptCore's framework to interpret a piece of javascript code in order to obtain a specific variable. My goal is to establish a GET reques ...

Guide to Displaying Items in Order, Concealing Them, and Looping in jQuery

I am trying to create a unique animation where three lines of text appear in succession, then hide, and then reappear in succession. I have successfully split the lines into span tags to make them appear one after the other. However, I am struggling to fin ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

What is the process for transferring ng-model values to a table in Angular?

My goal is to populate a table with JSON data using ng-repeat by clicking a button. I need to input either a first name or last name in order to display the results in the table. Is this the correct JavaScript function for achieving this? JavaScript Funct ...

Issue with Node Webpack identifying the "Import" statement

I'm diving into the world of Node and Webpack, but I'm struggling with getting my project to compile properly. Every time I try to load it in the browser, I encounter the error message: Uncaught SyntaxError: Unexpected token import. Let me share ...

Positioned footer without predetermined height

I am having trouble with positioning the footer so that it always stays at the bottom of the page. When there is not enough content on the page, the footer does not reach the bottom as desired. Additionally, the footer does not have a fixed height. Below i ...

What is preventing the action method from receiving parameters from the ajax call?

I am facing an issue with sending the FileHeadNo from ajax to my controller action as it seems the controller is not receiving the FileHeadNo parameter. $(function () { $("#txtReportNo").autocomplete({ source: function (reque ...

Implementing a fixed top navigation bar with jQuery to override default CSS properties

My latest project involves creating a WordPress site, and I recently found a way to fix my navbar at the top of the page as users scroll down. Here's the code snippet I used: (function( $ ){ var navOffset = jQuery("nav").offset().top; jQu ...

Refresh the Content of a Page Using AJAX by Forcing a Full Reload

I have a webpage that automatically updates a section using jQuery AJAX every 10 seconds. Whenever I modify the CSS or JavaScript of that page, I would like to include a script in the content fetched via AJAX to trigger a full page reload. The page is ac ...

JavaFX WebEngine pauses until ajax is finished

Currently, I am working on a JavaFX data mining application that heavily relies on WebView and WebEngine. The entire mining process involves two main steps. Firstly, the user navigates to a specific website using the UI in WebView to configure the search f ...

Node, Express, and Angular redirection problem encountered

I have a web application built with node, express, and angular. The app consists of two main pages - a user profile page and a login page. My goal is to redirect any user who is not logged in to the login page when they try to access the profile page. Howe ...

AJAX causes PHP file to receive empty values from HTML form

As a newcomer to AJAX, I am aiming to create a search feature that retrieves data from a database based on user input. Despite my efforts to debug the code multiple times, I have been unable to resolve the issue. Any assistance would be greatly appreciated ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

Error: Unable to return callback response from NodeJs function

I have a function that handles the process of reading a private key from the filesystem and generating a JWT token. The code successfully reads the file and creates a token, but it encounters an issue when attempting to callback to the calling function. De ...

Unable to retrieve the image

When trying to fetch an image, I encountered the following error: Failed to load resource: the server responded with a status of 404 (Not Found) TopBar.jsx import { useContext } from "react"; import { Link } from "react-router-dom"; ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

Retrieve the text input from its respective radio button

There are two radio buttons, each accompanied by an input text field. When a user selects a radio button, they can also enter some corresponding text. My inquiry is: What is the best method to retrieve the entered text for the selected radio button? ...