动态创建任意数量的顺序触发功能

问题描述

(JavaScript)我有一个函数,可以以一种很好的顺序方式处理玩家卡片:玩家,发牌人,玩家,发牌人。下面是该功能的一部分,该功能可将卡片顺序移至视口。

setTimeout(()=>{
    player1.style.top = `70%`;
    player1.style.left = `30%`;
    player1.style.transform = `rotate(${Math.floor(Math.random() * rotationMax)}deg)`;
    setTimeout(() => {
        dealer1.style.top = `8%`;
        dealer1.style.left = `30%` 
        dealer1.style.transform = `rotate(${Math.floor(Math.random() * rotationMax)+1}deg)`;
        setTimeout(() => {
            player2.style.top = `70%`;
            player2.style.left = `50%`
            player2.style.transform = `rotate(${Math.floor(Math.random() * rotationMax)}deg)`;
            setTimeout(() => {
                flippedCard.style.top = '8%';
                flippedCard.style.left = '44%';
            
        },200)},100)},200)

您可以看到此块仅适用于一定数量的卡(在这种情况下为4)。我对Java语言的理解还不够好,无法创建可以动态生成任意数量的待发卡的功能

有人可以指出我正确的方向吗?具体问题:您如何动态生成一个一个运行的任务。

解决方法

制作一张发牌人牌和一张玩家纸牌,并找出各自需要的left之间的差异。然后遍历数组,使用await进行延迟,以使代码平坦且可读:

const delay200 = () => new Promise(res => setTimeout(res,200);
const playerCards = [player1,player2];
const dealerCards = [dealer1,dealer2];
const playerLeftIncrement = 20; // eg: 30%,then 50%,then 70%; adjust as needed
const dealerLeftIncrement = 14; // eg: 30%,then 44%,then 58%; adjust as needed
const applyStyle = (card,left) => {
  Object.assign(
    card.style,{
      top: '70%',left,transform: `rotate(${Math.floor(Math.random() * rotationMax)}deg)`,}
  );
};
for (let i = 0; i < playerCards.length; i++) {
  applyStyle(playerCards[i],`${30 + i * playerLeftIncrement}%`);
  await delay200();
  applyStyle(dealerCards[i],`${30 + i * dealerLeftIncrement}%`);
  await delay200();
}
,

拥有一个看起来像这样的函数会很有用: callFunctionsWithDelays(functions,delays)

这样可以避免代码的嵌套外观,并使其易于动态生成。我会使用async / await语法编写此代码:

async function callFunctionsWithDelays(functions,delays) {
    for (i = 0; i < functions.length; i++) {
         functions[i].call()
         await new Promise(resolve,setTimeout(resolve,delays[i]))
    }
}