JavaScript callback animations utilize a callback function to trigger animations

I have created a custom animate function using three.js for 3D rendering. When clicking on the screen, the cube rotates based on the animation described in the function call. However, I noticed that if the cube is already animating under one animation and another animation is added, it does not flicker as expected. Instead, the last animation is halted and the new one takes over. Even though my callback function at the end shows that the old animation function was still running. So why does the cube not flicker when multiple clicks are sent?

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <script src="three-mini.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
    </style>
</head>

UPDATE 1:

In an attempt to understand this behavior, I added more meshes and animated them differently with subsequent clicks. Each mesh is first rotated, then moved forwards and backwards before rotating again. Interestingly, animating position does not halt the rotation animation, and animating one mesh simultaneously with another does not stop previous animations either. So, why does the animation not flicker when multiple animations are running on the same mesh and property?

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <script src="three-mini.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
    </style>
</head>

comment for WestLangley: Let me further explain the scenario. If I click once to start an animation from position.x = 0 to targetValue: '+=200', and then halfway through I click again to animate in the negative x direction starting from position.x = 100 and targeting '-=200'. I would expect both animations to run concurrently, resulting in the cube jumping left and right until the first animation completes. However, only the latest animation affects the mesh properties while the others seem to be processed "hidden"ly. This raises concerns about CPU cycles being wasted and difficulties in adding animations in callback functions. How can these "hidden" animation calls be prevented?

Answer №1

Although I'm not entirely clear on the current situation, what I can confirm is that several animations are running simultaneously even when the earlier ones are not visible. My primary concern here is the unnecessary utilization of processing power. To address this issue, I have introduced a suffix notation and now attach the animating functions directly to the object owning the animated property itself. For instance, if I am animating position.x, I create my animation function and assign it to position.x_animate and position.x_animate_alt alternatively. This approach allows me to effectively cancel any previous animation still in progress, thus preventing wastage of processor cycles. Below is the complete snippet of the animate function:

var animate = function(obj, prop, targetValue, length, callback) {

            var suffix = '_animate', altSuffix = '_animate_alt', thisSuffix = suffix, startTime = Date.now(), inverseLength = 1 / length, startValue = obj[prop];

            if( typeof targetValue === "string") {
                if(targetValue.substring(0, 2) === "+=") {
                    targetValue = obj[prop] + Number(targetValue.substring(2));
                } else {
                    targetValue = obj[prop] - Number(targetValue.substring(2));
                }
            }

            if(obj[prop+suffix] instanceof Function){
                obj[prop+suffix].cancelled = true;
                thisSuffix = altSuffix;
            }
            if(obj[prop+altSuffix] instanceof Function){
                obj[prop+altSuffix].cancelled = true;
                thisSuffix = suffix;
            }

            obj[prop+thisSuffix] = function() {

                var elapsed;
                if(obj[prop+thisSuffix].cancelled){
                    delete obj[prop+thisSuffix];
                    return;
                }
                elapsed = (Date.now() - startTime) * inverseLength;

                if(elapsed >= 1) {

                    obj[prop] = targetValue;
                    delete obj[prop+thisSuffix];
                    if( callback instanceof Function) {
                        requestAnimationFrame(callback);
                    }
                    return;

                } else {

                    obj[prop] = (startValue - targetValue) * (Math.cos(elapsed * Math.PI) + 1) * 0.5 + targetValue;

                    requestAnimationFrame(obj[prop+thisSuffix]);

                }

            };

            requestAnimationFrame(obj[prop+thisSuffix]);

        };

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

Issue with `npm run watch` failing to compile when the data source is turned

Currently, I am faced with a challenge while working on Laravel and utilizing various node packages for development. The issue at hand is my limited internet connectivity. Every time I attempt to execute npm run watch, it refuses to initiate unless I am c ...

JavaScript - Issue encountered while reaching the bottom of the webpage

While conducting tests using Firebug/Firefox, I am trying to execute a simple command that will scroll the page to the bottom. Here is the command: window.scrollBy(0,3000); Seems straightforward, right? When testing on certain websites like Yahoo.com ...

unable to employ angular ui-sortable

I got the most recent source code from https://github.com/angular-ui/ui-sortable. However, I am facing issues in using it. The demo.html file seems to be broken. Update: Upon inspecting the console when opening demo.html: Navigated to https://www.google. ...

Tips for managing the 'undefined' error in JavaScript when dealing with constantly changing deeply nested objects

Currently, I am developing a project using React with Formik for form handling and Yup for validation schemas. My current task involves validating a nested form to add a CSS class to the input if there is an error in the respective index of the nested fiel ...

Angular Material - Stick to the Top

Currently I am working with angular 4 along with angular material 2.0.0-beta.12. One thing I am aiming to implement is something known as "affix~" on the angular material website I am looking to create a layout similar to the image found here: https://i. ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

Having trouble loading data.json file in React.js and jQuery intergration

Having a background in mobile development, I am relatively new to web development so please excuse any amateur questions. Currently, I am working on a react.js project using create-react-app (which utilizes Babel). I am following a tutorial that requires ...

Javascript increasing the variable

Whenever I interact with the code below, it initially displays locationsgohere as empty. However, upon a second click, the data appears as expected. For example, if I input London, UK in the textarea with the ID #id, the corresponding output should be var ...

What is causing the search filter in the App.js code to malfunction?

After fetching a list of names from an array using the Fetch method, I attempted to implement a search filter by adding the resetData() method in my componentDidMount. Unfortunately, this resulted in an error as shown here: https://i.stack.imgur.com/1Z7kx. ...

What steps can I take to resolve the error message "TypeError: url.lastIndexOf is not a function" in three.js?

I am currently experimenting with loading a gLTF file in Three.js r105. After successfully loading the file, I decided to try changing the URL post-loading to see if it was possible. However, this decision led me straight into a problem. Initially, I atte ...

JavaScript: Conditional statement used to determine the target of a touched element

I'm currently working on enhancing the mobile responsiveness of a React project. As part of this process, I am attempting to ensure that certain JavaScript-driven style changes are only applied to elements that are not the target or a child of: <d ...

Can you please identify the TypeScript type associated with the return value of the match() method in String prototype?

I need help with creating a Regex in JavaScript const pattern = /S(\d+)E(\d+)/; // identifying characters between "S" and "D" const result = 'SE01E09'.match(pattern); How should I declare the result variable? I have attempted various ...

Please ensure to log out when the user exits the tab

I am looking for a way to automatically log out users from my Django site when they close the browser tab or window. Ideally, I want users to be forced to re-enter their username and password if they try to access the site again after closing it without cl ...

It's not possible to add additional options to the select input in a react

Hi there! I'm currently facing an issue while trying to retrieve a list of options from the backend, map them to another list of options, and add them to a main list. Unfortunately, my attempts have not been successful. Could anyone offer some advice ...

How can I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

Issue "RangeError: minimumFractionDigits value is invalid" when using ChartJS in a Next.js application

I'm currently working on developing an application utilizing react-chartjs-2.js. The functionality is smooth in my local environment, but when moved to production, I encounter the following error: Application error: a client-side exception has occurre ...

JavaScript code to prevent user from entering phone number

I operate a booking platform similar to AirBnB where users communicate with each other through messages on the site. My goal is to prevent users from sharing telephone numbers and email addresses within these messages. Currently, I am implementing a meth ...

Simply double-clicking in the 2D sheets view on the left panel will display PDF files in the Autodesk viewer

After discussing the information in this forum post, I have successfully displayed the 2D sheets view (left panel) in the Autodesk viewer for PDF files and other 2D files. https://i.sstatic.net/OFATj.png https://i.sstatic.net/WXMlT.png However, I am fac ...

Creating a WasmModuleBuilder in V8 that enables functions to return multiple values

I'm currently working on creating a wasm function using WasmModuleBuilder from V8: var builder = new WasmModuleBuilder(); builder.addMemory(5, 5, false); builder.addFunction("func", {params: [125,125], results: [125,125]}); builder.functions[0].addBo ...

Using Selenium to trigger the display of tooltips programmatically in Highcharts

I am faced with a situation where I need to automate some actions using selenium on a third-party website, which likely means I cannot utilize the highcharts API. Upon loading the third-party website, there is no tooltip element present in the HTML body. ...