How come repeating a call to an animation function in three js results in skipping certain animations?

I am trying to create a repeated animation sequence involving a sphere moving and then a rectangle, followed by displaying the number of times it has been repeated in a div called expected_output. However, I'm encountering an issue where the animation does not start as expected.

Here is the code snippet:

 var j = 1
var fieldNameElement = document.getElementById("expected_output");
function animator_repeat(){
    const animationClip = new THREE.AnimationClip(null, 3, [track1]);
    const animationClip1 = new THREE.AnimationClip(null, 3, [track]);
    const animationAction = mesh.userData.mixer.clipAction(animationClip);
    const animationAction1 = cube.userData.mixer.clipAction(animationClip1);

    animationAction.setLoop(THREE.LoopRepeat, 1);
    animationAction.play();
    mesh.userData.mixer.addEventListener('finished', () => {
        animationAction1.setLoop(THREE.LoopRepeat, 1);
        animationAction1.play(); 
        cube.userData.mixer.addEventListener('finished', () => {
            if(j < 6){
                fieldNameElement.textContent = "Number: " + (j+1).toString();
                animator_repeat()
                j = j+1
            }
        });
    })
}

View the jsfiddle for reference: https://jsfiddle.net/xgnj4fbh/6/

The issue can be observed with skipping steps 3 and 4 during the animation sequence.

Could someone please help me understand what's causing this problem?

Thank you!

Answer №1

The reason for this behavior is that a new event is added each time the animation completes. Whenever animator_repeat() is invoked, a new finish event is assigned to the mesh. Subsequently, each time the mesh finishes, the cube receives a new finish event, and upon completion of the cube, it triggers animator_repeat().

Consequently, on the 2nd completion of the cube, the finish event runs thrice, causing the value of j to jump from 2 to 5.

Possible solutions include removing old events before adding new ones, or utilizing named functions instead of anonymous ones.

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

Modifying button text with jQuery is not feasible

I'm facing a challenge with jQuery and I need the help of experienced wizards. I have a Squarespace page here: . However, changing the innerHTML of a button using jQuery seems to be escaping my grasp. My goal is to change the text in the "Add to car ...

Creating a countdown timer for a specific date and time using web technologies

I'm looking to create a timer countdown that is set to a specific date and time, such as June 1st at midnight. The code should display the remaining time until that date or time. ...

converting a JSON array into an object

I seem to be facing a challenge: I have a JSON list with rows of data and a JSON object. My goal is to iterate through the list and assign the rows to different objects within the JSON structure. The first and last elements in the list are empty, followe ...

Error: Encountered an unexpected token while trying to parse multiple form functions

I recently added the following submission function to my .js file: $( "form" ).on( "submit", function( event ) { event.preventDefault(); var data = $( this ).serialize(); $.ajax({ type: "POST", url: "content/rev/a_sub ...

Customize menu items in Angular ui-grid when right clicking on a cell

Seeking help with Angular UI-grid for a specific feature needed: I want to display a custom menu when a user right-clicks on a specific 'CELL/Column' in the grid, such as 'B' in the example image below. When the user right-clicks, the ...

React Material-UI: Trouble with Checkbox Toggle

I'm encountering an issue with my React code where the checkbox is not toggling when clicked. Here is the link to the codesandbox: https://codesandbox.io/s/inspiring-kirch-q6p4h The checkbox state initialization looks like this: const [checkbox, set ...

Determine whether a div contains any child elements

I am working on a piece of code that checks for the presence of the class "wrong" in any of my divs, and if found, displays a jQuery UI dialog box. My goal now is to enhance this code by adding a condition where it also checks for empty divs before showing ...

Specify a preset selection time in a TextField of time type in Material UI

I am looking to establish a default time for a textfield of type time in Material UI. My requirement is that before the user clicks on the picker, no time should be pre-set, but once they click, 08:00 should appear as the default time to choose from. View ...

save function ajax failure

I have created a function that adds a row after confirmation. The issue is that after submitting, the tables do not reload and show an error alert. In reality, the data is successfully saved but I need to refresh the page for the table to reload. Below is ...

What could be the reason for the lack of rendering in this imported React component using System.import?

I've been experimenting with dynamic code splitting using webpack 2 and react. As part of my testing, I decided to create a component that fetches code asynchronously: import React, { Component } from 'react' export class Async extends Com ...

Techniques for verifying phone numbers from various countries

The number of digits in a mobile number differs from country to country. I have tried using regular expressions, however, for example, India allows 10 digits, but this does not validate UAE, where the number of digits can range from 7 to 9. ...

What steps should be followed to construct a window identical to the one depicted in the attached image using HTML and CSS?

Check out this link to see the window style I'm trying to recreate using HTML, CSS, and Javascript. No Jquery needed. Thank you in advance. ...

Finding the console path in node.js

I'm currently developing a console application for node.js and I could use some guidance. When users install my console app using 'npm', they should be able to call it by typing 'program'. However, if the console is located at C:/U ...

Before inserting a string into JSON in PHP, the length of the string should be included

When sending a POST variable containing a JavaScript dictionary to a PHP file via Ajax, the value of this POST variable is being parsed as a PHP dictionary. However, I noticed that the length of each String value is added before the actual string in the PH ...

Developing a standard jQuery function for adding event listeners

Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc. In Moogle Maps, you can use .event.addListener(map, 'click', function()... or switch 'click' with 'drag ...

Ways to extract a specific value from a geojson object using the key name

After making a call to the back-end, I retrieved the below geojson data in the 'data' object. However, when trying to access the values of the 'type' and 'features' keys within the geojson, I encountered difficulties. data["g ...

Discovering the correct location within a complex JSON or array to perform updates using JavaScript (either AngularJS or vanilla JavaScript

I am currently facing a challenge where I need to search for a specific value within my complex JSON array and then update the corresponding object. Here is a snippet of my JSON array: var myArray = [{ "id": 5424, "description": "x ...

Improving mongo information using angularjs

Have an Angular and MongoDB application. This is a part of my API where I have POST and PUT requests. The POST request works fine, but when I send a PUT request, I get an error "Cannot set property 'typelocal' of undefined". However, the PUT requ ...

What is the most efficient way to iterate through an array to push properties into an object nested within another array?

I have been working on a small Angular application that functions as a scheduler, allowing users to input a Name, Start and End dates, and toggle a boolean checkbox through a form. One challenge I am facing is trying to assign the names entered by each use ...

Jquery Click function malfunctioning on testing environment

I'm facing a bit of challenge and could really use some assistance. I have this code snippet that functions perfectly in my test document, but once it's uploaded to the live server, everything loads correctly except for the fadeOut click function ...