AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them.

Currently, it seems like all the results are displaying and animating at the same time, but this might be due to my computer's speed.

Here is the code snippet:

JavaScript

$.ajax({
  type: 'GET',
  url: '/PersonSearch',
  data: {
    'search_value': search
  },
  dataType: 'json',
})
.done(function(json) {
  $('#main').html('');
  $.each(json, function(key, value) {
    var search = $('<div />', {
       id: 'search' + key,
       'class': 'search-item off',
       html: 
        '<div class="basic-info">' +
          '<span class="first-name">' + value.First_name + '</span>' +
          '<span> </span>' +
          '<span class="last-name">' + value.Last_name + '</span>' +
        '</div>' +
        '<div class="dropdown">' +
          '<span class="phone-number">' + 'PHONE: ' + value.Phone_number + '</span>' +
          '<span class="email">' + 'EMAIL: ' + value.Email_address + '</span>' +
          '<div class="box edit"><img src="../media/gear.svg"/></div>' +
        '</div>'
    }).appendTo('#main');
    setTimeout(function() {
      search.removeClass('off');
    });
  });
});

CSS

.search-item.off{
  opacity: 0;
  top: 8px;
}
.search-item{
  overflow: hidden;
  position: relative;
  opacity: 1px;
  top: 0;
  transition: .75s;
}

HTML

<div id="main">

</div>

The code adds search results with the class search-item off, and after loading, removes the off class to trigger the fade-in effect using CSS transitions.

I attempted to use setTimeout() on .appendTo('#main') without success.

I am looking to introduce a delay in posting each search result within the #main element to ensure a delayed execution of the fade-in animation.

Answer №1

Your concept seems promising, but it would be beneficial to introduce a slight delay in your setTimeout function. Gradually increasing the delay for each new result is recommended. A longer initial delay (e.g., 1000 or 1 second) can serve as a starting point before fine-tuning with shorter intervals.

setTimeout(function() { ... }, 1000 * index);

Below is an example snippet demonstrating the application of setTimeout to stagger calls to append:

$(function() {
  var $container = $('#container');
  $.each(['foo', 'bar', 'qux'], function(i, value) {
    setTimeout(function() {
      $container.append('<div>' + value + '</div>');
    }, 1000 * i);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="container">
</div>

Answer №2

Why not give it a try?

setTimeout(function() { ... }, 0);

This method ensures that your content is loaded completely before proceeding.

Answer №3

The reason for this phenomenon is that the setTimeout function operates asynchronously, causing the timeouts to start at different intervals such as 5ms, 10ms, 13ms, etc. and execute at similar times. To address this issue, you can declare a variable named timeout before making the ajax call, increment the timeout value for each iteration within the each loop, and assign this updated timeout value to the respective setTimeout. Below is an illustration of this concept (with excessive timeout values):

var timeout = 0;
$('div').each(function() {
  var $this = $(this);
  timeout += 1000;
  setTimeout(function() {
    $this.hide('slow');
  }, timeout);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>

Answer №4

Consider utilizing the timeout feature within the callback function of the $.each() method.

$.each(json, setTimeout(function(key, value) {...}, 1000))

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

Is there a way to create an image gallery layout similar to Pinterest using CSS?

I am currently developing a dynamic PHP gallery that will feature thumbnails with the same width but varying heights. These thumbnails will be arranged from left to right, so I would prefer not to use a traditional five-column layout. I suspect that achiev ...

Combining a complete hierarchy of Object3D/Mesh into one merged entity

I'm currently working on a project that involves dynamically generating trees using simple cubes for branches and leaves in the early prototype stages. Each tree consists of a hierarchy of cubes nested with rotations and scaling to create the final st ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...

Maintaining sequential order IDs for table rows even after removing records

I currently have a table structured as follows: <table> <tr> <td> <input type="hidden" name="help[0].id" /> </td> <td> <span class="tr-close">X</span> </tr> <tr ...

Unable to handle JQuery POST to PHP in success function

I am struggling with a jQuery post function that is supposed to call a PHP script in order to retrieve a value from the database. Although I can see in Firebug that the PHP file is being called and returning a 200 OK status, the success function in my JS ...

How do I start using Google Analytics: application.js, ga.js, or a beginner’s guide?

Hello there! I was wondering if anyone could provide a comprehensive guide or step-by-step tutorial on setting up Google Analytics with some examples. The information I found so far only covers signing up and obtaining a tracking code, but it doesn't ...

Executing function inside an Angular factory

I am currently working with an Angular factory that contains various functions. My goal is to use myService to retrieve data, and upon successful retrieval, call another function within the factory: myApp.factory('myFactory', function($http) { ...

Tips for utilizing vulnerable web scripts on SSL-enabled pages

After implementing SSL to secure my pages, I encountered an issue where one of my scripts no longer functions properly. Specifically, I had a script on my page that was used to display the visit count from this website. Previously, it was functioning fla ...

Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element. However, despite my efforts, I haven't been success ...

Is it possible to create a fluid-width layout with two columns that also spans the full

I have searched tirelessly through Google and stackoverflow, but I can't seem to find a solution to my specific problem. I need help creating a container div that can hold either one or two columns. The content is generated by a CMS and may or may not ...

Comparing the map function and for loop in the Puppeteer package for Node.js

I experimented with the Puppeteer package in NodeJS and noticed a significant difference in functionality between using the map function versus a for loop. Here is an illustration of what I observed: Using the map function: data.map(async(info) =>{ ...

Which specific html container or element can be found on the mymsn pages?

When accessing mymsn, users have the ability to personalize the content and layout of their webpage. I am curious about what type of container is being utilized for this customization - does it involve an html element, or perhaps javascript, or something e ...

Updating parts of a list using AJAX

Recently, I've encountered a challenge where I need to enable editing functionality on a table column from a database. The goal is to make the column editable when clicked and update the value when clicked out. To achieve this, I decided to utilize A ...

Every time I rotate my div, its position changes and it never goes back to

Trying to create an eye test by rotating the letter "E" when a directional button is clicked. However, facing an issue where the "E" changes position after the initial click instead of staying in place. Here is a GIF showcasing the problem: https://i.stac ...

Activate and deactivate button

I've tried multiple examples on this site for enabling and disabling a button using javascript with jquery, but none of them seem to work for me. Here is my current dilemma: <asp:TextBox ID="mytext" runat="server" onkeyup="enableButton(this, 3)"/ ...

Update the text for the filter search placeholder in the Ant Table component

Is there a way to alter the default placeholder text in the Ant Table? I've set up a functioning example in documentation but couldn't find any prop for customization besides the customized filter dropdown, which I didn't want to implement. ...

The navigation is designed to only show up as I scroll down the page, but ideally it should be visible

I am trying to make the navigation bar appear on page load instead of when I scroll down the page. Currently, I am using this jQuery code: <script type="text/javascript> $(document).scroll(function() { if ($(this).scrollTop() == 20) { ...

I am having trouble with my jQuery datatable Ajax call - instead of reaching the server, I am seeing an alert indicating

Looking for help with my web page. I have a table that needs to be populated using AJAX calls to the server-side method. I've implemented jQuery DataTables, and here's the code snippet: $(document).ready(function() { $("#tableUserList").DataTa ...

Spin picture and optimize margins

I need help rotating an image by 90 degrees that is positioned between two boxes. The issue I am facing is that the rotated picture overlaps with the two boxes in this scenario. Example 1: Incorrect formatting CSS: .box{ height:50px; width:200px ...

Enhancing the mobile menu with a feature that allows users to easily close the

I am currently designing a mobile menu for a website that I created using Wordpress with the Divi Theme. When the user clicks on a "hamburger icon", it triggers a fullscreen menu to open: mobile menu If you tap on "Termine", it will reveal a submenu: mo ...