Newbie in JavaScript - reinitiating my for loop journey

After running an animation in 4 steps, I want it to restart once all the steps are completed.

var aSteps = [
    {
        "x": "800",
        "y": "0"
    },
    {
        "x": "800",
        "y": "500"
    },
    {
        "x": "0",
        "y": "500"
    }, {
        "x": "0",
        "y": "0"
    }
];

var iStepsLength = aSteps.length;
for (var i = 0; i < iStepsLength; i++) 
{
    $('#P1').animate
    ({
        left: aSteps[i].x,
        top: aSteps[i].y,
     }, 1000);
}

I attempted to use an if statement to reset the count back to 0 after reaching the last step.

if (i == 3)
{
    i=0;    
}

However, this caused the browser to crash as it entered an infinite loop. I'm seeking guidance on how to rectify this issue.

Answer №1

.animate() has the ability to include a callback function that gets executed after the animation is complete:

function moveElements( index ) {
    $('#container').animate({
        left: elements[ index ].x,
        top: elements[ index ].y,
     }, 800, function(){
         if (index == 4)
         {
            index = 0;    
         }
         moveElements( index + 1 );
     });
}

moveElements( 0 );

Answer №2

Transform the for loop into a standalone function and execute it twice consecutively. UPDATE: Here's an example:

function runForLoop() { 
   for (var i = 0; i < stepsLength; i++) {
     $('#P1').animate ({ left: steps[i].x, top: steps[i].y, }, 1000); 
   }
}

You can then simply invoke the function whenever you need to initiate the loop like this:

runForLoop()

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 it possible to exclude specific URLs from CSRF protection in sails.js?

I am currently integrating Stripe with my sails.js server and need to disable CSRF for specific URLs in order to utilize Stripe's webhooks effectively. Is there a way to exempt certain URLs from CSRF POST requirements within sails.js? I have searched ...

Tips for managing onClick events within a conditional component

I am currently attempting to implement an onClick event on the data that I have selected from the AsyncTypeahead. My goal is to pass a callback function to the Problem component, which will only render if an item has been selected. However, after selecting ...

Loading message displayed in web browsers by banner rotation system

I'm currently working on a banner rotator function that seems to be showing a "loading" message continuously while running. Here is the code snippet for reference: var banners = ['../Graphics/adv/1.gif','../Graphics/adv/2.jpg']; / ...

Using the window.setInterval() method to add jQuery/AJAX scripts to elements at regular intervals of 60 seconds

I'm having trouble with automatically updating a div. I have a script that refreshes the page content (similar to Facebook) every minute. The issue is that this div is newly added to the page and contains some ajax/jQuery elements for effects. functi ...

Floating action button within a collapsible panel

I am having trouble placing a fixed-action-btn inside a collapsible body. It keeps appearing in the bottom right corner of the page instead of within the collapsible itself. How can I ensure that the button stays inside the body? Check out this link for r ...

Creating a multi-dimensional array in order to store multiple sets of data

To generate a multidimensional array similar to the example below: var serviceCoors = [ [50, 40], [50, 50], [50, 60], ]; We have elements with latitude and longitude data: <div data-latitude="10" data-longitude="20" clas ...

When I attempt to utilize the API, the JavaScript implementation of a <script src=...> element seems to interfere

Within one of my HTML files, I encountered the following line near the top: <script src="//maps.google.com/maps/api/js?key=apikey"></script> The API key is currently hardcoded in this file, but I would like to use a configuration option store ...

Locate the database user based on any parameter provided in the request

I need to search for users in the database using any of three different fields. In Postman, I have set up the following paths: http://localhost:8082/api/users/617473029f80eda3643a7fdd http://localhost:8082/api/users/Michael http://localhost:8082/api/use ...

The headers set in jQuery's $.ajaxSetup will be used for every ajaxRequest, even if they

Below are the parameters set for all ajax calls in the <head> of my document. (This is necessary to fix an iOS ajax bug referenced at $.ajaxSetup ({ cache: false, headers: { "cache-control": "no-cache" } }); I am wo ...

Hierarchy-based state forwarding within React components

As I embark on the journey of learning Typescript+React in a professional environment, transitioning from working with technologies like CoffeeScript, Backbone, and Marionettejs, a question arises regarding the best approach to managing hierarchical views ...

What is the best way to bind data to a textarea component and keep it updated?

I started using VueJS just a week ago for a new project. During this time, I have successfully created two components: * Account.vue (Parent) <!--This snippet is just a small part of the code--> <e-textarea title="Additional Information" ...

When setting an empty URL with Fabricjs' setBackgroundImage function, a null reference error occurs in the _setWidthHeight

Recently, I stumbled upon an article detailing a method to clear the background of a fabric canvas... canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)); In the development of my online design tool which utilizes Fabricjs 1.4.4, I have ...

"Enjoy a unique browsing experience with a two-panel layout featuring a fixed right panel that appears after scrolling

I am facing difficulty in designing a layout with two panels where the left panel has relative positioning and the right panel becomes fixed only after a specific scroll point. Additionally, I need the height of the right panel to adjust when the page scro ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

Node.js: Troubleshooting a forEach Function Error

I am encountering an issue with my nodejs script that is causing a "function not found" error after trying to insert data from json files into Firestore. How can I resolve this? Thank you for your help. Below is my code snippet: var admin = require("f ...

Guide on extracting nested JSON data values using JavaScript

{ "_id" : ObjectId("587f5455da1da85d2bd01fc5"), "totalTime" : 0, "lastUpdatedBy" : ObjectId("57906bf8f4add282195d0a88"), "createdBy" : ObjectId("57906bf8f4add282195d0a88"), "workSpaceId" : ObjectId("57906c24f4add282195d0a8a"), "loca ...

I am having trouble with the CSS and Bootstrap not being applied after printing

Once the submit button is clicked on the initial output page, the CSS styling disappears and only a simple default form page is displayed. This does not meet my requirements. Using inline CSS allows it to work, but external CSS does not. Can someone please ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...

Having Trouble with Axios PUT Request in React and Redux

I'm having trouble making a PUT request to the server. I understand that for a PUT request, you need an identifier (e.g id) for the resource and the payload to update with. This is where I'm running into difficulties. Within my form, I have thes ...

The result after calling JSON.parse(...) was not accurate

The following method is used in the controller: @RequestMapping(value = "channelIntentionDetails.html", method = RequestMethod.POST) public @ResponseBody Report getChannelIntentionDetails(@RequestBody SearchParameters searchParameters) { LOGGER.in ...