What causes the initial image in the Array to not loop on the first attempt?

Creating a basic animation with JavaScript here. Even though CSS keyframes are an option, they won't do the trick for this particular project. That's why I'm sticking to a JavaScript solution and included a status div to give you an idea of what's going on. Check out the JSfiddle below.

So, here is the HTML snippet:

    <div id="zero-walking"><img src="#" id="zeroImage"></div>
    <div id="statusDiv"></div>

And here is the JavaScript part:

    var index = 0;
    var zero = document.getElementById("zeroImage");

    var zeroArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png", "images/5.png", "images/6.png", "images/7.png", "images/8.png", "images/9.png", "images/10.png", "images/11.png"];

    zeroAnimate();

    function zeroAnimate() {

        zero.setAttribute('src', zeroArray[index]);

        index += 1;

        if (index == zeroArray.length) {
            index = 0;
        }

        var statusDiv = document.getElementById('statusDiv');
        statusDiv.innerHTML = zeroArray[index];
    }

    setInterval(zeroAnimate, 700);

Click here to view the JSfiddle demo!

Answer №1

This specific code block:

 index += 1;

 if (index == zeroArray.length) {
    index = 0;
 }

Must be placed at the conclusion of the function execution.

The issue lies in the fact that the operation index += 1 occurs prior to the statement

statusDiv.innerHTML = zeroArray[index];
, causing the initial value to be 1 instead of 0 upon reaching that point...

Answer №2

Consider relocating the index assignment operator to the bottom of your method in order to prevent skipping the 0 frame. Right now, you are first incrementing the index before performing any work.

Answer №3

At times, I find myself questioning the reasons behind my willingness to assist others. If you simply wish to iterate through those images, you can use this code snippet:

function iterateThroughImages(element, imageArray, timeInterval, shouldLoop){
  var index = 0;
  var loopTimer = setInterval(function(){
    element.src = imageArray[index++];
    if(index === imageArray.length){
      shouldLoop ? index = 0 : clearInterval(loopTimer);
    }
  }, timeInterval);
}
iterateThroughImages(document.getElementById('zeroImage'), zeroImageArray, 700, true); // continuous looping

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

Connect my Vue.js model data to the object that will be used for submission

I need help figuring out how to bind data from my input field into my Vue.js model. I've tried putting the UnitName inside the model but it's not working. Can someone provide some guidance on how to achieve this? new Vue({ el: "#app", da ...

Interactive User Input and Display

Participants are required to provide their name within a form. <p>Name <font color="red">(required) </font> <input name="flname" required="required" placeholder="Your Name" </p> This particular solution allows for sample text t ...

Jspsych: Centering and aligning 3 p tags to the left on the page

Feeling pretty stuck at the moment. Here's what I have visually right now: https://i.sstatic.net/FUzgM.png I added a caption in Comic Sans and an arrow using MS Paint. Each line with color swatches is wrapped in a p tag. The goal is to center thes ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Troubleshooting: Bootstrap PopoverX functions failing

I've been attempting to make the bootstrap extension popover X function properly () I created a JS fiddle (http://jsfiddle.net/wp80d5ux/2/), but unfortunately, the popover doesn't appear to be loading. Here is the example I have: Could it be t ...

Updating a div's border using JavaScript

I recently generated a div element dynamically through code. var Element; Element = document.createElement('div'); My goal now is to modify the right and bottom borders to "#CCCCCC 1px solid". I aim to achieve this without relying on any exte ...

What is the best approach to determine the value of a textbox in an array for each row of

I am trying to display the total sum of values for each row in a data array. There are 5 rows of data, and I need to calculate the results for each one. Can someone assist me in solving this? function calculateTotalValue(){ var total = (document.get ...

What is the correct way to generate an await expression by utilizing recast/esprima?

I have an issue with a JavaScript function export const cleanUp = async () => { await User.destroy({ where: {} }); }; I am attempting to add a line below await User.destroy({ where: {} }) using recast.parse(`await ${module}.destroy({ where: {} } ...

Having trouble getting JavaScript to select a stylesheet based on time?

I am attempting to implement two different styles based on the time of day. Here is the code I am using to select the CSS file depending on the current time: <script type="text/javascript"> function setTimedStylesheet() { var currentTim ...

Remove the negative value by using jQuery subtraction function

My XML looks like this <b> <a>4205.0</a> <d>-152.22</d> </b> The values I have extracted are as follows var a = parseInt($(element).find('a').text()); var d = parseInt($(element).f ...

Using Javascript or jQuery, focus on a div containing a paragraph element with a particular text

I've been struggling for hours trying to figure out how to select a div that contains a specific p element. HTML <div class="NavBar_Row_Button2"><p>DONATE</p></div> <div class="NavBar_Row_Button2"><p>CONTACT</p ...

How can you ensure a div stays at the top or bottom of a page based on the user's scrolling behavior?

Hello there! While I know there have been many questions regarding sticking a div to the top or bottom while scrolling, my particular issue is a bit more specific. My dilemma is that I am looking for the div to stick either to the top or the bottom based ...

retrieve AJAX data from the document

After successfully implementing AJAX with assistance from a previous question, I am interested in creating a separate file to house my functions in order to maintain clean code. Despite not finding any helpful resources online, I am determined to explore t ...

Is there an issue with Ajax connecting to the database?

I have created an HTML file where I need AJAX to connect to the database in the background and fetch the selected city based on the user's pre-selected country. Essentially, I want the database to load all the cities in the drop-down menu automaticall ...

the method of utilizing JavaScript to showcase an HTML form

I have created a form for entering an employee's skills. Below the form, there is a link to add a new skill. When this link is clicked, the form should be displayed again. My code looks like this: <html> <head> ...

Utilitarian pool method yields the output from the specified callback function

As a beginner in nodejs, I am currently experimenting with generic-pool and mariasql. My code is functioning well. However, I recently enclosed my code within a function, and I am unsure about the proper way to handle events in nodejs to retrieve the resul ...

Steps to insert a button onto the Gmail compose toolbar using a Chrome extension

Exploring the realm of Chrome extensions, I am endeavoring to integrate a button into Gmail's compose bar akin to this example. Despite experimenting with various Gmail APIs, I have yet to discover a suitable solution. If anyone has insights on how to ...

Combining and adding together numerous objects within an array using JavaScript

I'm looking to combine two objects into a single total object and calculate the percentage change between the two values. I'm encountering some difficulties while trying to implement this logic, especially since the data is dynamic and there coul ...

Leveraging Dynamic Information within a Regex Pattern

I have a unique collection that appears as follows: listA = ["Physics","English","Chemistry","Biology","History","Human Values","None"] The website displays a textArea for users to input data like :- Hello, I really enjoy studying <<English>&g ...

Generate a JavaScript variable in real-time and leverage it to retrieve the corresponding JSON response

After receiving a JSON response from an API as depicted in the image below: https://i.sstatic.net/5eq43.png I encountered an issue where the same column_code is used in both the variable_meta section and the data part of the response. This column code act ...