Using recursive setTimeout in Javascript may not always utilize the entire final JSON object that is returned

My current approach involves making recursive calls to a URL until it returns either a success or reaches the maximum limit of tries. Below is a compact version of the relevant code:

function doSomething(numRetries) {
    $.post('someURL', {retry: numRetries},
        function (data) {
            if (data.value == 1) {
                displayResults(data.message, data.value);
            } else if (data.value == "retry") {
                setTimeout( function() { doSomething(data.retries) }, 1000);
            } else {
                displayResults(data.message, data.value);
            }
        },
        "json"
    );
}

If the initial call to 'someURL' results in data.value being equal to 1, then the displaySuccess function is executed. On the other hand, for any other result (e.g., 0), the displayFailure() method will be called successfully.

The issue lies in the recursive aspect. Despite initiating retries and incrementing the value for retries while calling doSomething(), any returned data afterwards remains unused.

For instance, when the retry timeout within 'someURL' is set to 3, I can observe through Firebug:

post('someURL', 0) returns JSONified (value = "retry", retries = 1)
post('someURL', 1) returns JSONified (value = "retry", retries = 2)
post('someURL', 2) returns JSONified (value = 0, error = "Display this error!")

However, despite the value being 0 (not "retry"), an alert() from displayFailure indicates that error = [undefined]. The JSON parsing seems to be functioning correctly according to Firebug.

EDIT: In order to reflect reality more accurately, modifications have been made to the doSomething function. These changes should not introduce any uncertainties. Additionally, the actual return values from the post calls are as follows:

{"success":"retry","retryCount":"1"}
{"success":"retry","retryCount":"2"}
{"success":0,"errormsg":"The request is taking longer than expected, but should be completed soon. Please try again in 15 minutes."}

Finally, here is a concise version of the displayResults() function:

function displayResults(text, status) {
    $('#dispElem').queue(function(next) {
        $('#dispElem').html(text);
        if (status == 1) {
            $('#dispElem').addClass("success");
        } else {
            // Hide and show random elements
        }
        next();
    }).fadeIn().queue(function(next) {});
}

Answer №1

Ugh.

The dreaded error of mixing up uppercase and lowercase letters that I somehow managed to overlook until I had no choice but to rewrite it for optimization.

Appreciate everyone's feedback and helping me thoroughly inspect, or shall I say comb through, my work more closely.

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

Creating two dropdown menus from a PHP array

Currently, I have a PHP array structured like this. $food = array ("Fruits" => array("apple","mango","orange"), "vegies"=> array ("capsicum", "betroot", "raddish"), "bisucuits"=>array("marygold", "britania", "goodday")); My task is to create two ...

Input a new value into the registration field to update it

My current task involves adding a new text field to a React form using a button. I need this new input text field to be able to store data on a register. How can I go about setting this property? Typically, when creating a text field, you would utilize co ...

Alternative for Jquery: a new Hash Table solution using Prototype JS

Greetings everyone! I have experience as a prototype JS developer but now I am transitioning to jQuery for work/client reasons. One feature I really liked in Prototype was the Hash class, such as var h = new Hash();. However, I understand that jQuery doe ...

Is it possible to inject JavaScript into the DOM after it has been loaded using an AJAX call?

I have a specific div element identified by the id #id1 that contains clickable links. Upon clicking on these links, an AJAX call is made to retrieve additional links from the server. My current approach involves replacing the existing links within #id1 w ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

While the Mongoose aggregate query is functioning properly in MongoDB, I am encountering difficulties in converting it to a Mongoose

Here is the JSON structure provided: [{ "_id" : ObjectId("626204345ae3d8ec53ef41ee"), "categoryName" : "Test Cate", "__v" : 0, "createdAt" : ISODate("2022-04-22T01:26:11.627Z"), "items" : [ { ...

"Creating a duplicate of an element by utilizing the `next`

I have a dilemma involving two divs within a section of my project - one div is dynamically created while the other exists statically. My goal is to transfer the non-dynamically created div into the one that is generated dynamically. let adContainer = $ ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

Assign a value to an Html.HiddenField without tying it to the model upon form submission

I have two classes, SubsidiaryClient and Client, that are related in a one-to-many manner as depicted below. Currently, I am utilizing MVC 5 for development. In the Create SubsidiaryClient page, to retrieve the ClientID, you need to click on the browse bu ...

Despite providing the correct token with Bearer, Vue 3 is still experiencing authorization issues

I am working on a project that involves Vue 3 with a Node Express back-end server and Firebase integration. On the backend server, I have implemented the following middleware: const getAuthToken = (req, _, next) => { if ( req.headers.authori ...

Can anyone explain to me how to render attributes of a tag in Vue? I'm curious about how v-for interacts with HTML

<ul> <span class="tabs" :class="{ activeTab: selectedTab === tab }" v-for="(tab, index) in tabs" @click="selectedTab = tab" :key="tab"> {{ in ...

"Hey, do you need a see-through background for your

Currently, I am implementing the JS library found at . Unfortunately, I am struggling to make the background transparent or any other color. It appears that the issue lies in the fact that the tab styles are being overridden by the JS library whenever the ...

When utilizing the http.post method, the req.body is not being populated as expected

I am puzzled by the fact that the req.body appears to be empty... app.js utilizes the body-parser middleware() var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var index = require('./routes/in ...

Tips for customizing the font color in Material UI Typography

Is it possible to change the color of only this text to red? return <Typography style={{ color: 'red' }}>Login Invalid</Typography> I came across this online solution, but I am unsure how to implement it as there is no theme={color ...

How come the styles in my CSS file aren't being applied to my images based on their class or ID?

When I apply a className or id to my img tag in my JavaScript (using React.js) and then add a style that references that id or class, the style does not get applied. However, when I do the same for a div, everything works perfectly fine. <--JavaScript- ...

What steps should I follow to set JSONP as the dataType for a request in an Angular $http service?

I have a good understanding of how to use jQuery's $.ajax: $.ajax({ url: //twitter endpoint, method:"GET", dataType:"jsonp", success:function() { //stuff } }); Is there a way to set the JSONP datatype for an angular $http service reque ...

While executing a for loop, the variable $.ajax is found to be null in Javascript

When I click on a button with the function btn-book, there is a for loop inside it that fetches data from Ajax. Despite knowing that the data holds values, I constantly receive null. Below is the code snippet for the onclick event: $('#mapContainer&a ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Is it possible to utilize the router.query feature in a function within Next.js?

Running into a problem with my Next.js page. I'm attempting to utilize the request params in a function, but it keeps coming up as undefined. I've exhausted all my troubleshooting options. I already know that there's no need to include id i ...

Socket.on seems to be malfunctioning

Currently, I am in the process of creating a message board for practice purposes and have successfully implemented notifications and a chat application using socket.io. My next goal is to add basic video call functionality, but I have encountered some dif ...