How to make multiple animations trigger in sequence on the same element using JavaScript?

I'm new to JavaScript, and working on a startup application. I'm trying to write code that will cause an animation to execute multiple times (in sequence) on the same text element, with the text changing between animations. The text change and second animation should not occur until the first animation is complete, and so on.

With the code that I've written, the text changes a few times over the course of a single animation, then hangs indefinitely. I'm assuming it's an issue with the async/await or the animationend listener... does anyone with more experience (basically everyone, haha) have a direction to point me in? I'd appreciate any input!

Here's my code with the console.log() statements removed:

async function initAnim() {
    const userAvatarBattleEl = document.querySelector(".userAvatarBattle");
    const chalAvatarBattleEl = document.querySelector(".chalAvatarBattle");
    const dialogueEl = document.querySelector(".dialogue");
    
    userAvatarBattleEl.classList.add("userAvatarAnim");
    chalAvatarBattleEl.classList.add("chalAvatarAnim");
    dialogueEl.classList.add("vs-fadeAnim");

    await waitforAnimation(dialogueEl);
    await waitforAnimation(userAvatarBattleEl);
    await waitforAnimation(chalAvatarBattleEl);
    dialogueEl.classList.remove("vs-fadeAnim");

    await setDialogue("First text");
    await setDialogue("Second text");
    await setDialogue("Third text");
    await setDialogue("Fourth text");
    await setDialogue("Fifth text");

}

async function setDialogue(text) {
    const dialogueEl = document.querySelector(".dialogue");
    dialogueEl.textContent = text;
    dialogueEl.classList.add("dialogueEnter");
    await waitforAnimation(dialogueEl);
    dialogueEl.classList.remove("dialogueEnter");
}

async function waitforAnimation(element) {
    return new Promise(resolve => {
        function handleAnimationEnd() {
            console.log(`The animation for ${element.classList} is finished!`);
            element.removeEventListener('animationend', handleAnimationEnd);
            resolve();
        }

        element.addEventListener('animationend', handleAnimationEnd);
    });
}
1 Answers

To make multiple animations trigger in sequence on the same element using JavaScript, you can follow these steps:

  1. Ensure that each animation triggers only when the previous one has completed.
  2. Use async/await functions to handle the sequence of animations.
  3. Add event listeners for the 'animationend' event to know when each animation has finished.
  4. Remove the event listeners after each animation completes to avoid any conflicts.

In your provided code snippet, you seem to be on the right track with using async functions and 'animationend' event listeners. You can modify your code to handle the sequence of animations correctly by following the steps above.