如何解决动态创建任意数量的顺序触发功能
(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]))
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。