gpt4 book ai didi

javascript - 避免 JS 中的顺序动画回调 hell

转载 作者:行者123 更新时间:2023-12-01 02:39:54 25 4
gpt4 key购买 nike

我有一个网络项目,我想对五个彩色 div 的不透明度进行动画处理,使它们按顺序“闪烁”,然后用户会按相同的顺序单击它们(就像西蒙说的那样)。当用户单击按钮时演示序列开始,并且该按钮也会淡出,因此只能单击一次。我的代码是这样的(仅用于演示动画,目前不关心用户响应):

function circleBlink(elem, callback) {
elem.animate({'opacity':'0'}, function() {
elem.animate({'opacity':'1'}, function() {
if (callback && typeof callback === 'function') {
callback();
}
});
});
}

function runThrough() {
circleBlink($('.sequence-options > .red-orange'), function() {
circleBlink($('.sequence-options > .blue'), function() {
circleBlink($('.sequence-options > .yellow'), function() {
circleBlink($('.sequence-options > .green'), function() {
circleBlink($('.sequence-options > .purple'));
});
});
});
});
}

$('.start-btn').click(function() {
$that = $(this);
$that.animate({'opacity': '0'}, function() {
$that.addClass('hidden');
});
runThrough();
setTimeout(runThrough, 5000);

});

代码按原样工作正常,但我想知道是否有更简洁/更高效/最佳实践的方法来重构它。我正在使用 jQuery,但不想为此特定项目引入任何其他动画库或插件

最佳答案

您可以为返回 Promise 的 animate 创建一个包装函数,并将 circleBlink 转换为返回 Promise 的函数。您还可以使用箭头函数来避免 that = this 的丑陋:

const animateWithOpacity = (jqElm, opacity) => new Promise(resolve => {
jqElm.animate({ opacity }, resolve);
});
async function circleBlink(elem) {
await animateWithOpacity(elem, '0');
await animateWithOpacity(elem, '1');
// async function will automatically return promise that resolves when end is reached
}

async function runThrough() {
const classes = ['red-orange', 'blue', 'yellow', 'green', 'purple'];
for (const className of classes) {
await circleBlink($('.sequence-options > .' + className));
}
}

$('.start-btn').click(function() {
animateWithOpacity($(this), 0)
.then(() => $(this).addClass('hidden'));
runThrough();
setTimeout(runThrough, 5000);
// might also be able to `runThrough().then(runThrough)` if the timing is right
});

关于javascript - 避免 JS 中的顺序动画回调 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50431389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com