Is it possible to apply a delay function to JQuery's AjaxStart/Stop events?

As I was working on my single-page app, I thought about adding a spinner and gray background to provide feedback to users while processes are loading. I discovered JQuery's AjaxStart() and AjaxStop() functions, which allow me to display the spinner during any Ajax calls in the app. Here is an example of how I implemented it.

<div class="overlay">
    <div id="loading-img"></div>
</div>

Using JQuery:

$(document).ajaxStart(function () {
    $('.overlay').delay(3500).show();
}).ajaxStop(function () {
    $('.overlay').hide();
});

In terms of styling:

 #loading-img {
        background: url(http://preloaders.net/preloaders/360/Velocity.gif) center center no-repeat;
        height: 100%;
        z-index: 20;
    }

    .overlay {
        background: #e9e9e9;
        display: none;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        opacity: 0.5;
    }

Although the code works and the spinner shows with the gray background, there was a slight issue where the spinner would briefly appear for half a second before being delayed. I attempted to use the delay() method to hold off on displaying the spinner, but it didn't work as expected. I wanted the spinner to only appear after 3 seconds. I'm unsure if there is an error in my code or if there is a better method to implement the spinner and gray background. Any suggestions would be greatly appreciated.

Answer №1

One alternative approach is to implement a timer that can be stopped if the data loads before the set timeout.

var timer;

$(document).ajaxStart(function () {
    timer = setTimeout(function() { $('.overlay').show(); }, 3500);

}).ajaxStop(function () {
    clearTimeout(timer);
    $('.overlay').hide();
});

With this implementation, you can ensure that the progress indicator is only shown when necessary and handled correctly.

Answer №2

The .delay() method is designed to work on effects that can be queued for execution.

It's important to note that only subsequent events in a queue will be delayed; for instance, the no-arguments forms of .show() or .hide() will not be affected as they do not use the effects queue. -jQuery .delay()

Make sure to specify a duration when using .show/hide()

Check out the Demo

$('.btn1').on('click', function() {
  $('#overlay1').delay(3500).fadeIn(750).delay(2000).fadeOut(750);
}); // this looks better

$('.btn2').on('click', function() {
  $('#overlay2').delay(3500).show(750).delay(2000).hide(750);
});
body {
  position: relative;
}

.overlay {
  height: 100vh;
  width: 100vw;
  background: rgba(0, 0, 0, .3);
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  text-align: center;
}

.overlay::after {
  content: url(https://loading.io/spinners/flat-ball/lg.flat-bouncing-circle-loading-icon.gif);
}
<button class='btn1'>FadeIn/Out</button>
<button class='btn2'>Show/Hide</button>
<div id='overlay1' class='overlay'>FadeIn/Out</div>

<div id='overlay2' class='overlay'>Show/Hide</div>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

The server returned a 500 Error when attempting to send a JSON object to an .ASMX

Short and sweet question: Why do I get a 500 error when passing a JSON object to an ASMX webservice? If I define the params as individual variables (e.g. int ID, int OrderHeaderID), I don't encounter the error. I'm puzzled because I've succe ...

optimal method for displaying HTML strings with components in Vue

My website is a Blog/News site featuring posts that contain HTML content stored in the database. In addition to posts, I also want to include elements like sliders which cannot be generated using v-html. I explored Vue's Render Functions to find a so ...

Is there a way to trigger a confirmation function for form submission exclusively when clicking one specific submit button, and not the other?

Here is the layout of my form: <form action="newsletter.php" name="newsletter" id="newsletter" method="post"> <input type="submit" value="Submit" class="c-btn" id="submit_value" name="submit_value"> <input type="submit" value="Send" cla ...

Enhancing the visual appeal of HTML code in "view Source" by injecting it using a System.Web.UI.WebControls.Literal

I am currently placing code within a literal in the following manner. ImageItem.Text = string.Format("<div class=\"thumb\"><img src=\"{0}\" width=\"132\" height=\"99\" /><a class=\"more\"> ...

Do not refresh the ajax content

I'm using Ajax to dynamically load HTML content into a div container. The content is loaded when an element with the class "link" is clicked, as shown below: $(".link").click(function () { $('.link').removeClass('current'); ...

The request.files property in express-fileupload is consistently coming back as undefined

I am trying to achieve the task of uploading a file from my browser and sending it via POST to an Express.js application, which will then download the file using express-fileupload. Here is the client-side JavaScript code I have written so far: // Triggere ...

"How can I perform a expressjs database query based on a specific user's

app.get('/user/:id', function(req, res){ fetchData(req.params.id, res); }); function fetchData(id, res) { connection.query('SELECT * FROM data WHERE name = ?' , function(err, rows){ res.render('users', {users ...

How can we extract word array in Python that works like CryptoJS.enc.Hex.parse(hash)?

Is there a method in Python to convert a hash into a word array similar to how it's done in JavaScript? In JavaScript using CryptoJS, you can achieve this by using: CryptoJS.enc.Hex.parse(hash), which will provide the word array. I've searched ...

Unable to make changes to the data

Journey Route::resource('/videofile', 'VideoController'); VideoController public function update(Request $req, $id){ $video = Video::findOrFail($id); if($req->hasFile('UserVideo')){ $vid = $req->file(& ...

What are the steps to create offline documentation for sails.js?

I am looking to integrate offline sails.js documentation into my system. You can find the official documentation for sails.js maintained at this Sails.js Documentation. According to their documentation, they use doc-templater for building the documentati ...

Position items within the dynamically generated div without appending them

Utilizing JavaScript, I dynamically generate a line but struggle to position two balls at both the 1/3 mark from the beginning and end. For reference, please view the image below. I aim to have two balls appear upon pressing enter in the input box. Despite ...

What is the best way to enable horizontal scrolling for textarea overflow in a smooth manner like input, without any sudden jumps?

Currently, I am interested in utilizing a one-line textarea (with rows=1 and overflow-x:hidden;) similar to input type="text. However, I have encountered an issue where the content scrolls with "jumps" while typing inside it: https://i.stack.imgur.com/Rzf ...

Information fails to show up upon navigating to a different page

Having trouble with a survey form that utilizes ajax to call data. When the user clicks cancel, I want it to navigate to another page displaying a list of data using ajax in listview format. While the navigation part is successful, the issue lies in not di ...

Please provide the text input for the specified version numbers (1.1, 1.2, 3.0, etc.)

I'm currently working on a form that includes a section for searching by version number: <label class="formLabel">Version</label> <html:text property="valueVersion" styleClass="value" tabindex="11"/> <br/& ...

Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct. Any assistance would be greatly appreciated. CURRENT ISSUES: [resolved]I am unable to determine why the duration ...

Obtaining a variable from within two nested functions

I'm looking for a solution where I can retrieve a variable from inside a function using an ajax call. For example: function returnStuff(){ $.ajax({ //do something }).done(function(response){ return response; }) return response; } The ...

Modifying the maximum value of a number field attribute in jQuery after a successful action

As I continue to learn jQuery, I encountered a situation with the following form: <form class="simple-checkout" enctype="multipart/form-data" method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>"> <input type="hidd ...

Manipulate and scale with jQuery

I am currently utilizing the jQueryUI library with its Draggable and Resizable functionalities to resize and drag a div element. However, I am encountering some unexpected behavior where the div jumps outside of its container upon resizing. How can I resol ...

Retrieve Content from a Different Web Page Using Ajax

I recently received permission from another website to pull their RSS feeds, and now I'm trying to figure out what to write in TAG1 and TAG2. This is the specific issue I'm facing: Here is the HTML code (it's an ajaxed page) <!doctype ht ...

Images in gallery slider are excessively large

Hello, this is my very first post on stackoverflow. Please forgive any atypical elements in this post. I have a Django Website with a gallery slider, but I am facing an issue where the images appear way too big. You can view them here: I have dedicated n ...