The image sequence animation only loads once and does not continue indefinitely

Here is my code snippet: I have a sequence of 15 images that should load one after the other in a loop with a specific time interval. However, I am facing a bug where the images keep playing infinitely when the page loads, but I want them to play only once. I'm unable to fix this issue, can someone please help me solve it?

onload = function startAnimation() { 
  var frames = document.getElementById("animation").children;
  var frameCount = frames.length;
  var i = 0;
  setInterval(function () { 
      frames[i % frameCount].style.display = "none";
      frames[++i % frameCount].style.display = "block";
  }, 100); 
}
#animation img {
    display: none;
}
#animation img:first-child {
    display: block;
}
<div id="animation"> 
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging01.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging02.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging03.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging04.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging05.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging06.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging07.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging08.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging09.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging10.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging11.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging12.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging13.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging14.png">
  <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging15.png">
</div>

Answer №1

@pratik, here is a helpful solution for you: Using clearInterval in the following way will resolve your issue:

if(j === 15) {
  clearInterval(interval);
}

Check out this example below:

onload = function startAnimation() {
            var animDiv = document.getElementById('animation');
            var x = document.createElement("IMG");
            x.setAttribute("id", 'test');
            x.setAttribute("src",
                "http://jumpingfishes.com/dancingpurpleunicorns/charging01.png");
            animDiv.appendChild(x);

            var i = 1,
                j = 2;
            var interval = setInterval(function () {
                var y = (i < 10) ? '0' + i.toString() : i.toString(),
                    z = (j < 10) ? '0' + j.toString() : j.toString(),
                    url = document.getElementById('test').src;
                document.getElementById('test').src = url.replace(y, z);
                i++;
                j++;
                if (j === 16) {
                    clearInterval(interval);
                }
            }, 100);
        }
#animation img {
  display: none;
}

#animation img:first-child {
  display: block;
}
<div id="animation">

</div>

Answer №2

To stop the animation, simply use the clearInterval(); function.

onload = function stopAnimation() { 
    var frames = document.getElementById("animation").children;
    var frameCount = frames.length;
    var i = 0;
    var myInterval=setInterval(function () { 
       if(i==frameCount-2){
         clearInterval(myInterval);
        }
        frames[i % frameCount].style.display = "none";
        frames[++i % frameCount].style.display = "block";
        
    }, 100); 
}
#animation img {
    display: none;
}
#animation img:first-child {
    display: block;
}
<div id="animation"> 
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging01.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging02.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging03.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging04.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging05.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging06.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging07.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging08.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging09.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging10.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging11.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging12.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging13.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging14.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging15.png" />
</div>

Answer №3

To stop a running interval, be sure to use the clearInterval() method.

Take a look at this sample:

Keep in mind that intervalEnd is the threshold number for stopping the interval once the i value reaches it.

onload = function startAnimation() { 
    var frames = document.getElementById("animation").children;
    var frameCount = frames.length;
    var i = 0;
    var intervalEnd = 100;
    var intervalId = setInterval(function () { 
        frames[i % frameCount].style.display = "none";
        frames[++i % frameCount].style.display = "block";
        if (i >= intervalEnd)
          clearInterval(intervalId)
    }, 100); 
}
#animation img {
    display: none;
}
#animation img:first-child {
    display: block;
}
<div id="animation"> 
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging01.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging02.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging03.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging04.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging05.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging06.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging07.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging08.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging09.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging10.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging11.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging12.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging13.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging14.png" />
    <img src="http://jumpingfishes.com/dancingpurpleunicorns/charging15.png" />
</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

Ensure YouTube iframe remains visible above all other elements on mobile devices at all times

Currently, my method involves utilizing YouTube for embedding videos and incorporating certain elements that should display on top of the video when clicked on. Regrettably, this functionality operates flawlessly on desktop browsers but encounters issues ...

Checkbox selection limitation feature not functioning correctly

Having trouble with my checkbox question function - I want to limit the number of checkboxes that can be checked to 3, but it's still allowing more than that. I suspect the issue lies with latestcheck.checked = false; This is my typescript function: ...

Importing a JavaScript file into another JavaScript file

var FS = require('fs'); var Path = require('path'); var Jsonfile = require('jsonfile'); var search = function () {}; search.prototype.projectContainerDirPath = null; /* * interface */ search.prototype.setPaths = function ...

Customizing color schemes of bootstrap buttons and dropdown-toggle elements

My button group looks like this: HTML <div class="btn-group"> <button type="button" class="btn btn-default btn-xs red-outline-button"> Sync </button> <button type="button" class="btn btn-default btn-xs gold-outline-button" da ...

Change to the parent frame using webdriver

I am facing an issue while trying to switch to the parent frame or iFrame using webdriver.js. Although I have implemented a function that works, it only goes up to the second level of frames. When attempting to switch to the parent frame from a deeper fr ...

Emulate clicking a radio button (using PHP and JS)

For the past week, I've been struggling to solve this issue with no luck. I admit that I am new to this area, so I ask for your patience. My current problem involves using TastyIgniter, an online food ordering system. In order to add items to the car ...

Is there a way to remove the excess white space beneath my content without resorting to using overflow-y: hidden?

I am struggling to eliminate the excess white space below the body of my web page in order to make it fit perfectly within the view of a web browser. Adding height helps with vertical alignment but leaves unwanted white space. I need a solution that doesn ...

Angular Bootstrap multi-typeahead component glitches

Currently, I am utilizing the bootstrap angular typehead feature. When using it for a single input field, everything functions as expected. However, upon attempting to implement multiple instances, I encounter an issue where one dropdown interferes with th ...

Remove an array key from a MongoDB collection

I am currently working with mongoDB and my JSON data (stored under the table name "student") appears as follows: [{ name : "John", subjects:["English", "Maths"] }, { name : "Winsel" ...

In the IE7 standards mode, table cells with no content will have a height of 1px

When utilizing IE7 standards mode within IE9, empty table cells are automatically assigned a height of 1px. As a result, elements positioned beneath the table appear lower on the page than intended. To view an example of this issue, refer to the code provi ...

Trouble initiating a jquery function in componentDidMount in a React component

I have encountered an issue with my ReactJS application. The $(document).ready(function(){}); function stops working after I switch paths using React Router Dom. In order to find a solution, I turned to Google and came across this helpful article: React- ...

Repeated HTML/CSS Elements with an Eye-Catching Image Header

I managed to get a header working, but the process was quite unsightly. Is there a more elegant approach to achieving this? My goal is to have a continuous header with an image centered within it. Essentially, I need a repeating background image, with my ...

Toggling dropdown menus with conditional Jquery statements

I am experiencing some discomfort. :) I've been working on a calorie calculator that includes a dropdown for various dietary preferences. Currently, when a user clicks the button, the dropdown appears and disappears when clicking outside the button. ...

Using the jasmine framework to create conditional test cases

Currently, I am working on Jasmine and my goal is to ensure that the test cases run only when the site's response status is okay (200). If the site fails to load, I do not want the test cases to execute. To achieve this, I am checking the site's ...

The animation in Three.js may come to a halt when the "skinning = true" setting is employed alongside THREE.ShaderMaterial

Currently, I am developing a game using WebGL and three.js, and I am in need of a skin shader for my character models. However, I have encountered a problem where if I use THREE.ShaderMaterial, the animation stops. Can anyone provide assistance or guidance ...

Button to access overlay menu on my map with OpenLayers 3

I am trying to add a menu button on top of my map that, when clicked, will display a window. I have created the map div and the overlayMenu button div, but unfortunately, the button is not showing up where I want it to. I would like the button to be locate ...

The type 'MutableRefObject<undefined>' cannot be assigned to the type 'LegacyRef<HTMLDivElement> | undefined'

I have created a customized hook that takes a ref object and observes its behavior: import { useState, useEffect, MutableRefObject } from "react"; const UseOnScreen = (ref: MutableRefObject<undefined>) => { const [isIntersecting, setI ...

How can I utilize the Json data retrieved through the findById method in my code?

My current project involves creating an API that retrieves data from Patients (id and name), Physicians (id and name), and Appointments (id, phyId, patId, app_date) in order to display the patients scheduled to see a specific physician. To achieve this, I ...

Building a table with the appendChild() method

I'm a beginner in the world of programming and I've been given a task to create a table of objects. I managed to do it using a certain method, but now I'd like to try creating it using the appendChild method. function addObject() { var ...

How can I align a div in a vertical manner if it is displayed as a circle?

This is the creation I have come up with: This is the design I am aiming for: Below is the code I have written: <div id="OR"><span style=" vertical-align: middle;background:blue;">OR</span></div> Here is the corresponding CSS: ...