The functionality of this javascript setTimeout is quite peculiar when it comes to working with ajax requests

I have created this script to monitor the progress of an import script. The script is designed to execute a function that makes an http request every X seconds.

function checkImportProgress() {
//if(import_status != 'finalizat') {
    alert("Checking Import Progress");
    setTimeout(function() { return updateImportProgress(); }, 2000);
    setTimeout(function() { return updateImportProgress(); }, 4000);
    setTimeout(function() { return updateImportProgress(); }, 6000);
    setTimeout(function() { return updateImportProgress(); }, 8000);

    //setTimeout(function() { checkImportProgress(); }, 400);
//}
//else {

//}
}

This script was used for testing purposes with comments included to indicate the intended functionality. Various combinations of setTimeout calls were tried, including using quotes, not using quotes, and using or not using anonymous functions.

var xmlhttp_import_progress;
function updateImportProgress() {
xmlhttp_import_progress=GetXMLHttpObject();
if (xmlhttp_import_progress==null) {
    alert ("Browser does not support HTTP Request (xmlhttp_import_progress)");
    return;
}

var url="crm/windows/import_progress.php";  
url=url+"?sid="+Math.random();

xmlhttp_import_progress.onreadystatechange=function() {
    if (xmlhttp_import_progress.readyState == 4) {
        progress_resp = xmlhttp_import_progress.responseText;
        progress = progress_resp.split('_');
        import_num_completed = progress[0];
        import_total = progress[1];
        import_status = progress[2];
        message = 'Import Progress: ' + import_num_completed + ' / ' + import_total;
        //document.getElementById("import_message_body").innerHTML = message;
        alert(progress_resp);        
    }
};
xmlhttp_import_progress.open("POST",url,true);
xmlhttp_import_progress.send(null);
}

This section contains the main logic of the checkImportProgress function.

When running the script, I receive the "Checking Import Progress" alert at the start of the import process. However, the alert displaying the progress details only shows up after the import process has completed (even though it continues to maintain the 2-second interval as intended by the setTimeout calls).

The PHP script in the AJAX request simply fetches session variables set by the import script and sends them back to JavaScript for display (such as number of imports completed out of total, number failed, etc).

Any suggestions on why this behavior occurs?

Answer №1

xmlhttp_import_progres.readyState == 4)
is true only once the request is complete. This means that your alert dialogs will appear after the request has finished processing.

It's important to note that you cannot predict when the server will respond, so setting a specific time interval for alerts may not be reliable.

If you need a function to update periodically, consider using

setInterval(function(){...}, 2000)
.

EDIT

Additionally, make sure to add var when defining the XMLHTTP object like this:

var xmlhttp_import_progres = GetXMLHttpObject();
. By declaring it globally, only one instance of the object will be accessible.

Answer №2

Here, could you attempt to make a slight modification:
Please review the response above, however, the following code will provide clarity:


function progress_import() {
//if(import_status != 'finalizat') {
    alert("progress_import");
    setTimeout(function() { return update_progress_import(0); }, 2000);
    setTimeout(function() { return update_progress_import(1); }, 4000);
    setTimeout(function() { return update_progress_import(2); }, 6000);
    setTimeout(function() { return update_progress_import(3); }, 8000);

    //setTimeout(function() { progress_import(); }, 400);
//}
//else {

//}
}

AND

var xmlhttp_progress_import = [];
function update_progress_import(i) {
    xmlhttp_progress_import[i]= GetXMLHttpObject();
    if (xmlhttp_progress_import[i]==null) {
        alert ("Browser does not support HTTP Request (xmlhttp_progress_import)");
        return;
    }

    var url="crm/windows/import_progress.php";  
    url=url+"?sid="+Math.random();

    xmlhttp_progress_import[i].onreadystatechange=function() {
        if (xmlhttp_progress_import[i].readyState == 4) {
            progress_resp = xmlhttp_progress_import[i].responseText;
            progress = progress_resp.split('_');
            import_num_c = progress[0];
            import_num_t = progress[1];
            import_status = progress[2];
            message = 'Progress import: ' + import_num_c + ' / ' + import_num_t;
            //document.getElementById("body_import_message").innerHTML = message;
            alert(progress_resp);        
        }
    };
    xmlhttp_progress_import[i].open("POST",url,true);
    xmlhttp_progress_import[i].send(null);
}

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

HTML5 Advanced API Integration with Vimeo

After setting up my Vimeo account and app for video upload, I received approval. However, when I attempted to upload a video to the Vimeo server, I encountered difficulties. I am struggling to understand how OAuth functions. Please see below for the co ...

Is history.pushState capable of more than just making an xhr request?

I've hit a roadblock in my current project. The issue I'm facing is getting a registration page to load. The XHR request is returning the output of the PHP code, which is causing problems. My goal is to have it load as a document rather than an ...

In React-Redux, the reducer is programmed to only ever return the initial state

When implementing Redux in my React app, I noticed that the reducer always returned false as the initial state. Thank you for your answer. [UPDATE]: I made the following change: let newState = {...state} However, the reducer still returned false. This ...

Struggling to generate fresh vue components

Having trouble registering new components in my Vue app. I have successfully registered some components, but when I try to register a new one, I encounter the error: Unknown custom element: <store> - did you register the component correctly? For re ...

How to access selection range styles using JavaScript

It is common knowledge that we can retrieve the selection of text in JavaScript using the following method: var range = window.getSelection (); However, how can we obtain the style of this selection? For example, when I select bolded text or italicized ...

ng-if directive in AngularJs will not function properly if the condition text includes a space

I encountered an issue while attempting to set values in AngularJS UI grid based on the row.entity values. To address this, I created a cellTemplate that evaluates the row values and applies text styling accordingly. Code Snippet var statusTemplate=&apos ...

The issue arises when attempting to utilize ExpressJS middleware in conjunction with NextJS Link feature

Incorporating Next with Express routes, I have set up a scenario where /a should only be accessible to authorized individuals, while /b is open to the public. ... other imports... const app = next({ isDev }) const handle = app.getRequestHandler() async f ...

The initial request is replaced by new information

Trying to fetch data for autocomplete in Laravel. Controller: public function collection_search(Request $request) { $term = $request->search; $serveurapObj = new Serveurap(); $result = $serveurapObj->collectionAutocomplete(); ...

While using .map() to display videos from an array, the button ends up playing all videos instead of only the selected

Within this component, I am presenting an array of YouTube videos utilizing react-player. The issue I'm facing is that when the custom play button is clicked, all videos in the array play and pause instead of just the selected one. I am currently uti ...

Layer added to map by Mapbox encountered an error during the process

I encountered an error that looks like this: https://i.sstatic.net/TI4HO.png When running the following code snippet: map.on('load', function () { map.addLayer({'type': 'scattermapbox', &ap ...

Retrieve information using JavaScript and save it within a PostgreSQL Database table

I have received data from a device in HEX format as shown below: <Buffer 00 cc> My goal is to convert this into TEXT format and store the value in a PostgreSQL database. However, I am encountering an error message while trying to process it for dat ...

Ways to add elements to a non-existent index in an array

I am facing an issue while attempting to form sets of objects in an array and generating a new set if the item is not already present. The structure of the data looks something like this: [ { "order": orderData, "items": itemData }, { "or ...

Tips for populating an array with boolean values when a checkbox change event occurs:

I am looking to fill the answers array with boolean values. The checkboxes on my form are generated dynamically, but there will only be four of them. When a checkbox is unchecked, its corresponding value in the answers array should be false; when checked, ...

Use JavaScript to swap out various HTML content in order to translate the page

I am currently facing a challenge with my multilingual WordPress website that utilizes ACF-Field. Unfortunately, WPML is not able to translate the field at the moment (2nd-level-support is looking into it). As a solution, I have been considering using Java ...

Error Encountered: Server Issues with php and ajax

While testing my files on a server, I encountered a 500 Internal Server Error. Interestingly, everything worked smoothly with MAMP (local) and I didn't face any errors at that time. Below is the code snippet that caused the error: <?php includ ...

Implementing a dynamic loading strategy for Google reCAPTCHA based on language selection

I have a unique application that requires the selection of one language out of four options (English, French, Dutch, español) in a form. Below the language selection, the Google reCaptcha is displayed. I am looking to dynamically load the reCaptcha scrip ...

Dropdown boxes that fetch data from a database in a cascading manner

Currently, I am working on creating two dropdown boxes that will be dynamically populated from a database using PHP and Ajax. The first dropdown menu will have only one option available, but selecting it should trigger the population of the second dropdown ...

Eliminate JSON data that pertains to dates that are either in the past or future

I am working on integrating upcoming classes and past classes components into my application. I have successfully stored the schedule of classes and can retrieve them using backend services. However, I need to display only the upcoming classes in one compo ...

Displaying mysqli results within a div while incorporating an onclick event for a javascript function that also includes another onclick event for a separate javascript function

I'm struggling to figure out the correct way to write this script. Can someone please guide me in the right direction or suggest an alternative method? I've searched but haven't found any relevant examples. I am fetching information from a ...

Modify URL parameters in Vue.js based on specific conditions to remove key-value pairs

Currently, I am working on a filter feature where I need to append query parameters to the URL based on user selections. If a user chooses a specific option, I want to modify the query string accordingly. Here's an example of my current URL structure: ...