Delay the execution using Javascript/jQuery, remove the last element from the DOM

Within a jQuery AJAX call, I am using a $.each() loop. Each element in the response data triggers the addition of a portion of HTML to a container class in my index.html file.

To view the code and ensure proper formatting, visit the codepen here as the pasted version may not display correctly due to mobile formatting issues.

$.each(responseData, function(i, item) {
    /*
    if(i > 4){
        $($("section").last()).remove();
    }
    */
    try{
        username = item.user.name;
        user_text = item.text;
        imgURL = item.user.profile_image_url;
        hashtags = item.entities.hashtags;
        let hashtagsDiv = ""
        if(hashtags.length > 0){
            hashtagsDiv = "<div class='row'><div class='col s10 offset-s2'>HASHTAGS: "
            for(i = 0; i < hashtags.length; i++){
                hashtagsDiv += "#"+hashtags[i].text+"; ";
            }
            hashtagsDiv += "</div></div>"
        }
        $("<div class ='row'>\
            <div class ='col s12'>\
                <section class='card-panel grey lighten-5 z-depth-1'>\
                    <div class='row valign-wrapper'>\
                        <div class='col s2'>\
                            <img src=\"" + imgURL + "\" alt='profile_pic' class='circle responsive-img'>\
                        </div>\
                        <div class='col s10'>\
                            <span class='black-text'> @" + username + " says: " + user_text + "</span>\
                        </div>\
                    </div>\
                    " + hashtagsDiv + "\
                </section>\
            </div>\
        </div>").prependTo(".container").slideDown();
        $(function(){  
            window.setTimeout(5000);
        });
    }  
    catch(err){
        console.log("ERROR: " + err.message);
    }
});

The prependTo() method targets the .container class within a <section> tag in my HTML file. The elements are added as expected, with the latest one appearing at the top upon page reload. This behavior mimics a queue, stacking elements from the bottom up.

Presently, there are two issues that need attention:

  1. The setTimeout() function does not produce the desired delay. All elements appear simultaneously, and I am struggling to implement a delay between each iteration. The intention is for each element to slide down every few seconds.

  2. Upon reaching a count of i > 4, I intend to remove the last element from the DOM in each cycle. This would maintain a maximum of 5 visible elements, with the oldest one removed at the end of each cycle to keep the queue updated. However, uncommenting the relevant if block causes all elements to disappear from the screen.

I would greatly appreciate assistance in resolving these two issues. Thank you!

Answer №1

Uncertain about the intent behind $($("section").last()).remove()? It seems like you may be aiming to delete the freshly added div, in which case the selection of section is not appropriate. Assuming all responseData is received prior to executing the function, I have devised a solution below. Additionally, I have adjusted the timing for the new row to be prepended to 1000ms.

To achieve your goal, place the setTimeout outside the prepending function and increment the time for each index. I highly suggest going through all the details provided in this MDN page to grasp a clear understanding of setTimeout.

Below is a simplified working example:

let responseData = [0, 1, 2, 3, 4, 5, 6, 7]

$.each(responseData, function(i, item) {
  setTimeout(function() {
      try {
        $(`<section>Section Number ${i}</section>`)
          .prependTo(".container")
          .slideDown();
      } catch (err) {
        console.log("ERROR: " + err.message);
      }
      
      if (i > 4) {
        console.log(i)
        $("section").last().remove()
      }
  }, i * 1000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "container"></div>

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

Generate a new core element featuring the top 10 users

In my app, I have a function that sorts users in the mobile_user table based on their earned points and assigns them a rank. This function is triggered every time an http request is made. Now, what I want to achieve is creating a new root node called lead ...

Issue with webpack failing to inject variables

I have encountered an issue while using the npm package got, which I am importing into one of my components. Strangely, when I run everything through Webpack, Safari is the only browser showing the error message: SyntaxError: Unexpected keyword 'cons ...

What is the reason that TypeScript does not automatically infer void & {} as the never type?

When TypeScript's void type is used in combination with other types through intersection, the outcomes vary. type A = void & {} // A becomes void & {} type B = void & '1' // B becomes never type C = void & 1 // C becomes never type D = void ...

Creating a Dynamic Input Validation Range with JQuery

Greetings and thank you for taking the time to review this! :-) The form validation is functioning correctly with required fields, but I am facing a challenge with setting up numeric range validation dynamically for an autocomplete feature. The JQuery val ...

Verify if a specific key is present in associative arrays

Can you please explain the correct way to check for the existence of a key in associative arrays? For instance: var mydata = { key1: '', key2: { subkey1: { subkey1_1: { value1: '' ...

MongoDB failing to enforce unique constraints on partial indexes

I have a set of data that looks like this: { name: "Acme co." add4: "", nationalNumber: "+13412768376" }, { name: "Acme Inc.", add4: "6345", nationalNumber: "" } My goal is to insert these records into a collection, but only if they are uni ...

What exactly is the concept of lazily installing a dependency?

The website here contains information about the changes in Ember 2.11. Ember 2.11 now utilizes the ember-source module instead of the ember Bower package. In the upcoming Ember CLI 2.12 release, Bower will no longer be installed by default but will only ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

Modify the role attribute on elements in real-time to enhance accessibility

On a German website, we have implemented a textfield with autocomplete functionality in a form. As the user types into the input field, a dropdown menu of suggestions appears for them to select from. It is crucial that this feature is fully accessible with ...

Utilizing Vue's Getter and Setter to manipulate data within the frontend, rather than relying on the raw values

I am completely new to Vue and finding it difficult to understand why I am facing this issue. Whenever I make a call to my backend in order to fetch some data, the response looks like this: id: Getter & Setter name: Getter & Setter season: Getter ...

Guide to authenticating with npm using various user accounts for different scopes within the same registry

I am facing an issue with setting up multiple npm authTokens for two different scopes on the same registry. @scope1:registry=https://registry.npmjs.org/ @scope2:registry=https://registry.npmjs.org/ //registry.npmjs.org/:_authToken=${NPM_TOKEN} I have atte ...

PHP - Utilizing a while loop to dynamically wrap content in a

I am facing an issue with wrapping the date and all events in one day within a div called "obal_date". The current implementation is not working as expected. The number of events can vary, but I need to group them by date. Can someone help me achieve this? ...

What is the best way to center align two inner divs within a container?

I've been working on achieving the following design: https://i.sstatic.net/ckC3j.png Just to clarify, the dashed line represents a guide indicating that both .inner-a and .inner-b are aligned in the middle horizontally and vertically within the imag ...

What is the best way to incorporate a countdown timer on an ASP.NET webpage?

Looking to display a countdown timer in the top right corner of my ASP page that starts from 00:00:30 and counts down to 00:00:00 before resetting back to 00:00:30. Does anyone have any suggestions on how to achieve this? ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Issue with change event not firing upon page load

In my production record creation page, I have implemented functionality to handle different line, shift, and date combinations. There are drop down menus for selecting the line and shift, as well as a jQuery date picker for selecting the date. One issue I ...

Struggling to properly interpret the unrefined data from Typeform's webhook

Utilizing the webhook feature of Typeform to convert results to JSON when a user submits the embedded survey is working perfectly when tested with RequestBin. However, after exposing my local app using ngrok with the command ngrok http 3000 and setting t ...

Initial loading issue with HTML5 Canvas in Android WebView

As I work on developing a HTML5 canvas-based game within a WebView of an existing application, I encounter a puzzling issue. Upon the initial run of the game, everything seems to be in order - logs indicate that it's ready and running, yet nothing is ...

I am looking to remove the target attribute from an anchor tag if it does not have a value assigned

To ensure W3C validation, I must remove the target attribute from all anchors where the target value is null. Here is the code snippet inside the body: <div> <a href="#" target="">home empty</a> <a href="#" target="blank">home&l ...

Troubles with Angular elements not aligning correctly when using the "display: block" property

When using an angular element for a directive with "display: block", it may not automatically take up 100% of the width of the parent container. In order to ensure that it does, the width must be explicitly set to "100%" in the CSS. Despite setting "width: ...