0

I have to use this js code to add an array by taking values from buttons that have been clicked. So, I stored them in an array to pass it in the function which will add to my main HTML. The problem I am facing is that it gets added into the array by each button I clicked but it will not give time for each element to execute. It directly shows the last element effect.

  // We create a Promise and return it
  new Promise((resolve, reject) => {
    const animationName = `${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve("Animation ended");
    }

    node.addEventListener("animationend", handleAnimationEnd, { once: true });
  });

var arrayOfButtonId = [];
var counter = 1;
$(".buttons-container").click(function (e) {
  var clickedItemId = e.target.id;
  //   var clickedItemValue = e.target.value;
  arrayOfButtonId.push(clickedItemId);
  arrayOfButtonId.forEach((index) => {
    console.log(index);
    animateCSS(".sample-display", index).then(() => {
      alert(" animation created successfully!");
    });
  });
});

This is the code I tried to implement .

Abhishek Kumar
  • 102
  • 2
  • 11

1 Answers1

0

Super classic question, you can't expect an asynchronous mechanism like a Promise (even with await, let alone with .then()) to work inside a synchronous Array method (forEach, map, filter, etc.) as explained here.

You need for and async/await :

$(".buttons-container").click( async function (e) {
  var clickedItemId = e.target.id;
  arrayOfButtonId.push(clickedItemId);
  
  for( let index in arrayOfButtonId){
    console.log(index);
    await animateCSS(".sample-display", index);
    console.log("animation created successfully!");
  }    
});

Also, drop the alert() because it's blocking your UI and kind of defeats the asynchronism purpose. Use console.log instead.

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • can we have to use for loop to iterate through each element of an array and then use setTimeOut for give duration to each element – Abhishek Kumar Dec 10 '21 at 13:15
  • Yes, you can `await new Promise( r => setTimeout(r, 1000));` – Jeremy Thille Dec 10 '21 at 13:18
  • Actually problem is that I have to pass each element after it shows the animation. Then next element will be added there to the main function. So in there is no available function to pass in setTimeout. – Abhishek Kumar Dec 10 '21 at 17:23