Implementing a loading animation effect using AJAX that requires a loop delay and sleep functionality

My jquery ui dialog is loaded via ajax with a partial view from the server. Initially, the dialog opens as a dialog-ajax-loader and then animates/grows to fit the content once the call returns.

The issue arises when the dialog content gets cached or the ajax call is too quick. This results in the content being loaded immediately into the ajax-loader-sized dialog without the ajax loader being visible at all. I have put a lot of effort into making this look great, so I can't accept this outcome. I want the ajax loader to be displayed for at least 1 second, or longer if the ajax call takes more time.

I've spent a considerable amount of time searching online for a suitable sleep() function, but it seems to come with a taboo. I decided to reach out here in hopes of getting some suggestions on how to best accomplish this.

The actual code is much more complex, but the concept goes like this:

 var mydialog = $("<div></div>").dialog({...Ajax loader settings...});

 var minimumTimeMet = false;
 setTimeout(function( ){ minimumTimeMet = true; }, 1000);
 mydialog.dialog("open"); //Open ajax loader

 $.ajax({ 
     cache: false,   //This helps but not always, sometimes the request is just too fast
     ....
     success: function(htmlContentResponse){

          while(!minimumTimeMet){
              //sleep here! However, thread cannot be 
              //blocked because the function set in setTimeout
              //above must executed to change minimumTimeMet = true 
              //and break out of this loop. 
          }

          mydialog.html(htmlContentResponse);  
          mydialog.animate({...Animate into new dialog settings ...});
     }

 });

Answer №1

Consider implementing a flag system before sending the request, along with setting a setTimeout of 1000ms. Make sure to clear the flag in the callback function.

var isReady = false;
var responseData;

setTimeout(function () {
    isReady = true;
    if (responseData) {
        handleAjaxResponse(responseData);
    }
}, 1000);

$.ajax({
    cache: false,
    success: function(data){
        responseData = data;
        if (isReady)   {
            handleAjaxResponse(responseData);
        }
    }
});

function handleAjaxResponse(data) {
    // Perform actions on response
}

By using this approach, the script will ensure that the ajax call waits for the setTimeout callback to execute if it completes early.

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

Connecting Vue component data to external state sources

I am facing a challenge with integrating a Vue component into a large legacy system that is not based on Vue. This component retrieves data through AJAX requests and displays information based on an array of database record IDs, typically passed at page lo ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

How do I create a clean HTML file when using the email editor with TinyMCE?

I was able to develop my own email editor, inspired by this particular example. To enhance user experience, I included a download button at the end of the file so that users can easily retrieve their edited content. The issue I'm facing is that tinym ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

What is the process for obtaining the updated file name of a file that has been saved using ajax AsyncFile

When utilizing the asyncfileupload ajax plugin from the ajax toolkit to save a file, I am running into an issue where the filename needs to be changed to prevent duplicates. To inform the user of the new filename after upload, I have implemented the follo ...

Issue with sender field in contact form and mailer function

Having issues with my contact form that has 3 fields and a textarea... I've used jQuery for validation and PHP to handle email sending. The contact form is functioning correctly, but the From field in the received emails is not displaying as expect ...

Doesn't seem like jQuery's .blur() is responsive on dynamically created fields

I am currently designing a login form that includes a registration form as well. Using jQuery, the email field is generated dynamically. The labels are positioned below the fields so that they can be placed inside the field. As the field gains focus or ha ...

What steps can I take to prevent receiving a 400 (Bad Request) error when using ajax PUT

Having an issue with sending data using JavaScript and AJAX. The objective is to send the data via PUT method to the server. var payload = 'id=' + id + '&brand=' + brand + '&model=' + model + '&country=' ...

Ensuring that only one field is selected with mandatory values using Joi validation

Is there a way to create a validation rule utilizing Joi that ensures if valueA is empty, then valueB must have a value, and vice versa? My current approach involves using Joi for validating an array of objects with properties valueA and valueB. Below is ...

Is it possible to transfer a variable from my javascript code to a jsp file?

Within a HTML file, I have created a variable in JavaScript consisting of an array with two entries - a latitude and a longitude. I am looking to use AJAX to send this variable and then utilize it in my JSP file to populate a form. Does anyone have any su ...

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

Firefoxx unable to communicate with server through ajax requests

My dilemma involves transmitting data to my server using the json data type with ajax. Oddly enough, in Firefox the server fails to receive any data at all, while in Chrome and IE the data is successfully transmitted and displayed on the server console. H ...

Interact with visible elements by automating mouse clicks with puppeteer

When attempting to click on various elements within a page, my goal is to do so only if they are visible. While achieving this in selenium with the is_displayed method was simple, I have struggled to find a similar approach in puppeteer. I attempted to imp ...

How to highlight text within an iframe using the mouse and displaying the selected text in a separate div

I'm currently able to select text with the mouse and display that selection in a div. However, I'm struggling to do the same thing when dealing with an iframe displaying a page on the same domain. Despite trying various solutions found here, I h ...

Tips on resolving JavaScript's failure to adjust to the latest HTML inputs

I'm working on a homepage where users can choose their preferred search engine. The issue I'm facing is that even if they switch between search engines, the result remains the same. I've experimented with if-then statements, but the selecti ...

Utilizing ASCII art in React: A guide to incorporating textual designs into your

I'm having trouble displaying ASCII images correctly on my React app. I've tried various methods, but nothing seems to maintain the form when rendered in the browser. <Grid container id="terminal_banner"> <Grid item ...

What is the best way to split an AJAX response into different variables and effectively retrieve each one of them?

When using AJAX to fetch data from a database and display it in a text box, most examples found online only show how to display the AJAX response in one text box. But what if we need to separate multiple PHP variables retrieved from the AJAX response and d ...

Using Jquery and AJAX to insert a PHP file into a DIV container

I am facing a challenge where I need to dynamically load a PHP file into a DIV element upon clicking a button, all without the page having to reload. If you refer to the 'Jsfiddle' document linked below, you will find further details and explana ...

javascript dynamic content remains unaffected by ajax call

I'm a beginner with javascript and I am using a PHP variable to create links dynamically. Here is an example of how the variable is set: $addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart(' ...

Utilizing styled-components or personalized components alongside cypress

Cypress selector made simple: just use cy.get('.myComp') and it will select <input className="myComp" />. But when it comes to styled-components... Perhaps we have to resort to using custom attributes like cy-data or cy-testid. Sadly, it s ...