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

What is the best way to create a delay so that it only appears after 16 seconds have elapsed?

Is there a way to delay the appearance of the sliding box until 16 seconds have passed? <script type="text/javascript"> $(function() { $(window).scroll(function(){ var distanceTop = $('#last').offset().top - $(window).height(); ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Is there a way to align these side by side?

Is it a silly question? Perhaps. But I can't seem to figure out how to align my text and colorpicker on the same line instead of two. Take a look at my fiddle. I've tried removing display:block and clear:both, but that didn't do the trick. H ...

Use jQuery to automatically update a variable every 5 seconds

For the first time, I am using django to build a webpage and facing a challenge in fetching the value of a variable from a .py file every 5 seconds. Here is the HTML code snippet: <!DOCTYPE html> <html> <head> <title&g ...

Error in Angular2: "Promise" name not found despite successful installation of global dependencies

I'm currently developing an application using Angular 2 and Node.js. I've already installed all the necessary dependencies specified in package.json. Inside this file, there is a postinstall command that should install the required dependencies m ...

Guide to prompting a browser to download a file using an XHR request

When it comes to downloading files from a server using an XHR request, how can I ensure that the browser initiates the download once the response is received? Additionally, which headers should be included by the server for this process to work seamlessl ...

The only React element that is rendered inside a for loop is the last one

I'm struggling with a function that is supposed to render an infinite number of strings as Comment components, but it only displays the last component. This is the function I'm working with: function displayComments(...comments) { for(let i ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

Leverage the Google Drive API for the storage of app-specific data

I'm currently developing a JavaScript application that runs on the client side and need to store a JSON object containing configuration details in a Google Drive Appdata file. Through the Google Drive API, I can successfully check for the file within ...

Using Vanilla JavaScript and VueJS to smoothly scroll back to the top of a div when a button is clicked

I have a VueJS-based app that features a multistep form with a next button. You can check out the functioning of the app here: My current challenge is ensuring that once the user clicks the next button, the top of the following question becomes visible. I ...

How can you deduce the type from a different property in Typescript?

I have encountered obstacles in my development process and need assistance overcoming them. Currently, I am trying to configure TObject.props to only accept 'href' or 'download' if the condition TObject.name = 'a' is met, and ...

Transferring information to PHP using AJAX and then populating the response in a text field

In the midst of creating a straightforward web form, I'm tackling the task of sending data from a text box to PHP using jQuery AJAX. My ultimate goal is to update a label on the HTML page with the response that has been manipulated through PHP. To ex ...

"Dealing with an unspecified number of fields in an ExtJS data model

I have a data model that is designed to accommodate various incoming data by keeping it generic and allowing for the addition of multiple meta data tags to my project. How can I effectively map these data fields to the Model or access them in the array w ...

The disconnection event in Node.js socket.io is not being triggered

I've been working on an app using socket io, but I'm having trouble with my disconnect trigger event. I followed the documentation to the letter, but it's still not functioning properly. Strangely enough, it was working just fine a few days ...

Issues with nested array filtering in JS/Angular causing unexpected outcomes

I am faced with a particular scenario where I need to make three HTTP requests to a REST API. Once the data is loaded, I have to perform post-processing on the client side. Here's what I have: An array of "brands" An array of "materials" An array o ...

Discovering the most recent Node.js version: A step-by-step guide

Is it possible to check the latest available Nodejs version using npm? While node -v allows us to see the current version, I am curious if there is a way to access the most recent version through JavaScript. For example, process.version can be used to vi ...

Obtaining the blog slug dynamically upon clicking with ReactJS

Currently, I am developing a project using Reactjs and Nextjs. One of the tasks at hand is to obtain the "slug" value after clicking on a blog post. However, at this moment, the value returned is undefined despite trying the following code: <h4 onClic ...

Looking to find the video code in the page source and figure out how to get the video to play

I have a requirement where I must embed the video code directly in a blog post. After figuring out the necessary code for the video and saving it in a html file named video.html, I encountered an issue when trying to upload the file to the blog. Only the ...

Leveraging PHP, AJAX, and MySQL within the CodeIgniter framework

I am currently venturing into the world of web development using the codeigniter PHP framework. My current hurdle involves a select dropdown on a page, populated with unique IDs such as 1, 2, 3 from the database. What I aim to achieve is, when a value is s ...

Developing a robust system for managing classnames

I have a question regarding the article I found on Quora about Facebook's CSS class names structure. They mentioned that both Facebook and Google use a build system to convert developer-friendly class names into shorter ones to save bandwidth and crea ...