Guide on executing a sequence of animations with the help of promises

In my current project, I am creating a Rubik's cube animation using three.js. The main challenge I am facing is implementing a function to shuffle the cube smoothly.

So far, I have successfully developed functions to animate single moves, such as rotating the right face by 90 degrees clockwise. Now, to shuffle the cube, I randomly select 5 moves and execute the corresponding functions one after the other. To achieve this sequential execution, I have decided to utilize promise chaining. However, the animations are currently occurring simultaneously instead of consecutively.

function shuffle(){
    let promise = Promise.resolve();
    for(let i = 0; i < 5; i++){
        promise = promise.then(randomMove);
    }
}
function randomMove(){
    let side = Math.floor(Math.random()*6);
    let turns = Math.floor(Math.random()*3);
    MOVES[6*turns+side][1]();
}
function r1(){
        let cubiesToRotate = cube.getCubiesByVID([].concat(cube.RIGHT_CENTRAL_CUBIES).concat(cube.RIGHT_CORNER_CUBIES).concat(cube.RIGHT_EDGE_CUBIES));
        let group = new THREE.Object3D();
        for(let cubie of cubiesToRotate){
            group.add(cubie);
        }
        scene.add(group);
        this.rotate(group,new THREE.Vector3(-1,0,0),90*Math.PI/180,0);
    }
function rotate(cubies,axis,angle,total){
        console.log(axis);
        if(total <= angle){
            total+=0.05;
            cubies.rotateOnAxis(axis,0.05);
            renderer.render(scene,camera);
            requestAnimationFrame(function(){
                cubeAnimator.rotate(cubies,axis,angle,total);
            });
        }
    }

Each function in the code follows a similar pattern:

1. Manipulate the positions of the cubies.

2. Call renderer.render to update the scene.

3. Use requestAnimationFrame to continue the rotation until the desired angle is reached.

While considering a delay between moves using setTimeout is an option, I believe there might be a more elegant solution. I am open to any suggestions or advice on how to achieve a smooth and sequential shuffle animation. Thank you.

Answer №1

In order to perform movements one after the other, you must create a new Promise after the previous one is resolved. Currently, your promises are being resolved immediately, causing them to occur simultaneously. To fix this issue, you can:

function shuffle(){
    let promise = Promise.resolve();
    for(let i = 0; i < 5; i++){
        promise = promise.then(_ => new Promise(resolve =>
        randomMove();
        resolve();
      ));
    }
}

A more efficient way to handle a series of movements is to utilize rxjs. You can achieve this by:

function shuffle(){
    const movements = []
    for(let i = 0; i < 5; i++){
      movements.push[randomMove]
    }
    from(movements).pipe(concatMap((callback) => callback()) 
}

By using concatMap, the next randomMove will only execute after the previous one has completed.

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

Tips for assigning a value to an Option element when the selection changes in JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http- ...

There appears to be an issue with the functionality of the JavaScript calculation function

Check out this JS Fiddle. I've tried my best in writing the script, but it just doesn't seem to work properly. If you could spare some time to review it and provide feedback on what I might be missing or doing wrong, I would greatly appreciate it ...

Steps to link a specific section of a Google pie chart:

I have a question that may be a little confusing, so let me explain. I recently used Google Charts to create a simple pie chart and it worked perfectly. Now, I am trying to figure out how to link each section/part of the pie chart to display a jQuery moda ...

Loading images in real-time from the server for an HTML gallery

Recently, I implemented a dynamic wowslider gallery that loads images from a specific folder. The issue I encountered is that all the images load simultaneously, causing a delay in loading time. My goal is to load the images one by one in order using JavaS ...

Having trouble with loading the contents of an iframe in JavaScript?

Within my website, there is a single Iframe that I set the src attribute for during the document.ready event. I have placed this iframe inside a jquery UI dialog, but now every time the dialog is opened, the Iframe reloads its contents. I would like this ...

Vue.js/Vuetify - Dynamically filter select options based on another select value

Is there a way to filter data in order to populate one select based on the selection made in another select? For example, if I choose a state from one select, can I have a second select loaded with all cities from that specific state? I am using vue.js and ...

When referencing an object in AngularJS that is defined within the $scope, it is important to

Imagine having a NameController implemented in AngularJS. You can define variables like so: this.name = 'Joe'; Alternatively, you could use: $scope.name = 'Joe'; I have a preference for accessing all variables using object notation: ...

What is the best way to transform this into an HTML readable code?

While browsing through a template, I came across this code and I'm unsure of how to get it functioning. I've tried removing the comments, but unfortunately it doesn't seem to be working as expected. li.dropdown.navbar-cart ...

Changing JSON information into a Javascript Array utilizing knockout

I have a JSON Array that includes various rules and values, but I want to convert it into a specific array format. Here is an example of the original JSON Array: AccessToFinancialServicesRule: {Clean: 3, Copy: 3} BoardParticipationRule: {Clean: 3, Copy: 3} ...

Transfer the data from the For loop to JavaScript

As I develop a survey form through the ASP.NET MVC structure, I encounter a phase where I extract the survey questions from a model to the view. The model I have created is as follows: [NotMapped] public class QuizForService { public int M ...

Issue with Accessing Subdomain Cookies on Express Backend Using CORS and Cookie-Parser

I am currently tackling a challenge in my MERN (MongoDB, Express, React, Node.js) application related to receiving cookies from subdomains in my Express backend. Despite implementing CORS and cookie handling successfully for a simple localhost origin, I am ...

Tips for transferring a JSON object from an HTML document to a JavaScript file

Here is the code snippet: <script id="product-listing" type="x-handlebars-template"> {{#each productsInCart}} <tr> <td> <div class="imageDiv"> <img ...

Passing the input value from an HTML file to views is proving to be quite challenging for me

Seeking assistance with creating an add to cart function in Django; encountering an error "POST http://localhost:8000/update_item/ 500 (Internal Server Error)". Any help would be greatly appreciated. Thank you! views.py def updateItem(request): data = js ...

403 Forbidden Error encountered when attempting to incorporate JavaScript

I have encountered an issue with my code where I am trying to grab a form from another website. The PHP code in the header is meant to sanitize the GET string in the URL for security purposes. Essentially, I have a page called order.html which functions pr ...

Discover the correct way to locate the "_id" field, not the "id" field, within an array when using Javascript and the MEAN stack

I am working on an Angular application that connects to MongoDB. I have a data array named books, which stores information retrieved from the database. The structure of each entry in the array is as follows: {_id: "5b768f4519d48c34e466411f", name: "test", ...

Unexpected Undefined Return in Request Parameters

Hey everyone, I'm currently working on setting up a mock API server using a JSON file with some dummy data. The first route I created is functioning perfectly: const express = require("express"); const router = express.Router(); const data = requir ...

Is there a way to switch tabs through programming?

Is there a way to switch between tabs using jQuery or JavaScript when using the tabbed content from ? I have tried using $("tab1").click(); I have created a fiddle for this specific issue which can be found at: https://jsfiddle.net/6e3y9663/1/ ...

How can I trigger a page postback in ASP.NET after downloading a file?

Here is my current scenario: The user clicks on a LinkButton, triggering a PostBack on the page. However, I also need to initiate a file download for the user simultaneously. To achieve this, I added the following code to the LinkButton: lnkPrint.Attri ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

NodeJS reference copying problem

After encountering an issue where changes to the original object were being reflected in a copy due to JavaScript referencing, I followed recommendations and updated my code as follows: const originalData = {...docid[0][0].Record} // or const originalData ...