What causes the inconsistency in time intervals in the loop?

My goal was to create a simple slider that loops through 3 images, with each image staying visible for 3 seconds before fading out and the next one fading in. However, I encountered an issue:
The first image can stay for 3 seconds, but once the loop starts, the subsequent images change immediately without waiting for the full 3-second interval. Why is it not maintaining the delay?
You can view the Demo here.

var i = 0;
var name = ['Cat', 'Dog', 'Duck'];

function next() {
  if (i > 1) {
    i = 0;
  } else {
    i++;
  };
  $('#loop').fadeOut(1000, function() {
    $(this).css('background', 'url("' + i + '.png")').fadeIn(1000);
    $('h1').html(name[i]);
  });
};
setInterval(next, 3000);
#loop {
  width: 300px;
  height: 300px;
  background: url('0.png');
}
h1 {
  padding-top: 310px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loop">
  <h1>Cat</h1>
</div>

Answer №1

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Loop Animation</title>
    <style type="text/css">
        #loop{
            width: 300px;
            height: 300px;
            background: url('0.png');
        }
        h1{
            padding-top: 310px;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="loop">
    <h1>Animals</h1>
</div>


<script src="https://code.jquery.com/jquery-3.0.0.min.js"
        integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0="
        crossorigin="anonymous">
</script>
<script>
    $(function (){
        var counter = 0;
        var animalNames = ['Cat', 'Dog', 'Duck'];

        var timerId = setTimeout(animateNext, 3000);
        function animateNext(){
            if (counter > 1) {
                counter = 0;
            }else{
                counter++;
            };
            $('#loop').fadeOut(1000, function (){
                $(this).css('background', 'url("'+ counter +'.png")').fadeIn(1000);
                $('h1').html(animalNames[counter]);
                timerId = setTimeout(animateNext, 3000);
            });
        };

    });
</script>
</body>


</html>

Answer №2

You have the option to utilize .queue(), .delay(), .promise(), or even recursion

$(function() {

var names = ['Lion', 'Elephant', 'Zebra'];

var images = ["http://placehold.it/300x300?text=Lion"
             , "http://placehold.it/300x300?text=Elephant"
             , "http://placehold.it/300x300?text=Zebra"]

function next() {
  return $("#loop")
    .queue("names", $.map(names, function(name, i) {
      return function(next) {
        $(this).css("background", "url(" + images[i] + ")")
        .find("h1").html(name).end()
        .fadeIn(1000, function() {
          $(this).delay(3000)
          .fadeOut(1000).promise().then(next)
        })
      }
    }))
    .dequeue("names").promise("names").then(next)
};

next();

})
#loop {
  width: 300px;
  height: 300px;
  background-repeat:no-repeat;
}
h1 {
  padding-top: 310px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loop">
  <h1>Lion</h1>
</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

Retrieve specific information from checkboxes within a form

I'm working on a form that includes multiple checkboxes populated with data from a JSON file using ng-repeat. After submitting the form, I need to retrieve the data from the checked checkboxes. How can I accomplish this in my controller after the form ...

I desire to activate the textbox only when the radiobtnlist value equals 1

I am trying to disable a textbox based on the selected value of a RadioButtonList in my code. However, the functionality is not working as expected and I am unsure why. <script type="text/javascript"> $(function () { $("#RadioButton ...

Retrieve the text inside the DIV that contains the clicked link

I'm facing an issue with my JS code: $(document).on("click", '.like', function (e) { $(this).parent().html("<a href = '#' class = 'unlike'><div class = 'heart'></div></a>"); ...

Navigating through a website with just a click and automatic scrolling

My website features a left navigation bar filled with 'a' tags linked to anchor tags. As you navigate through different pages, they may not have the same song list as the homepage. I want to implement a feature where clicking an 'a' ta ...

Is it possible to integrate a Neo4j Graph Visualization running on a virtual machine into my flask user interface?

My current setup involves running Neo4j on an Azure Virtual Machine and accessing the graph visualization through a web browser. In addition, I have developed a UI using Python with Flask that is currently running locally. I am interested in embedding th ...

Tips on sending an array to material-ui dataSource props

Currently utilizing material-ui for a component. I am facing an issue with the autocomplete component in material-ui where I intend to display a list of icon names along with the icons. When only passing MenuItem to dataSource, it results in an empty input ...

Using NodeJS to assign key-value pairs to a JSON object

I am currently working with a NodeJS script that receives data in the form of "key, value" pairs and I need to transform this data into a JSON object. The data is obtained using SNMP where the key corresponds to the OID. My goal is to efficiently map thes ...

Mobile responsiveness of Bootstrap navbar

Currently, I am in the process of constructing a Bootstrap 4 website using Jekyll. Each page features a jumbotron that serves as a hero header and everything is functioning smoothly.However, when I resize the viewport to a mobile size, the jumbotron ends u ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Tips for successfully transferring large amounts of data using XmlHttpRequest in ajax calls

I'm facing an issue with passing a large amount of data to the controller using XmlHttpRequest. Here's the code snippet I've implemented: var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = ...

AngularJS ui-router in HTML5 mode is a powerful combination that allows

Hey, I'm looking to implement HTML5 mode in my project. Here's how my file structure looks: mypage.de/mysub I can only make changes within the "mysub" directory. So far, I've added the following into my index.html: <base href="/mysub/ ...

How to Resolve ENOENT ERROR When Using fs.unlink in an Express.js Simple Application?

Currently, I am developing a basic blog using express.js. For managing the posts, I have opted for Typicode/lowdb as my database. The posts are created, updated, and deleted based on unique IDs stored in a data.json file. Additionally, I utilize the slug d ...

Apply bold formatting to the HTML text only, leaving the EJS variable untouched beside it

https://i.sstatic.net/X36eG.png Is there a way to format the text for "Guest signed up" and "Guests attended" in bold while keeping the values normal? Here is my current code: <li class="list-group-item">Guests signed up: <%= guestSignu ...

Choose a single conditional element by using the .each method in JavaScript

I am looking to choose just one article that meets a specific condition. In my code, I am using hourDiff==0 as the condition to be true. I am using the 'each' function to loop through the articles. I have set display:none for all articles in the ...

How can I retrieve individual form values within a loop using AJAX without mixing them up?

I am having an issue with my collection page where I have products listed in a loop. When I try to retrieve the value of each product using jQuery and ajax, it only shows the value of the first product whenever I click on any "add to cart" button. Here is ...

Transforming a hierarchical array into a string based on a specific condition

Seeking assistance in properly formatting data using the reduce method const testData = { a: [1], b: [2, 3, 4], c: [] }; Objective is to convert to: a=1&b=2,3,4 Current output: a=1&b=2,3,4& const createUrlString = params => Object.key ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

Creating a Future Prediction Graph with ECharts

I am looking to create a forecast chart that includes both Actual values (presented as a line chart) and projected values (displayed as a dotted chart). An example of what I have in mind can be seen here, created using Excel: https://i.sstatic.net/q18An.pn ...

How to include an href in a button using Pug without disrupting a form

Is there a way to create a button that redirects to my /leaderboard page once my quiz app submits? h1 Play Time 4 Trivia! button Go form(method='POST') ul each val in questions li ...

Perfectly aligning css tabs both vertically and horizontally with dead centering technique

Can you help me figure this out? Currently, the tabs in the HTML and CSS provided below are positioned close to the top of the screen. How can I adjust the markup so that the tabs are dead-centered (both vertically and horizontally) instead? Check out th ...