我的应用程序中有几个 setTimeout 函数在不同时间被调用(有些在页面加载后同时被调用)
我正在尝试找出一种压缩和增强此代码的方法。下面是我正在调用的 3 个 setTimeout 函数的示例,实际上我的应用程序中还有更多:
setTimeout(function () {
$('.itemOne').css({
'visibility': 'visible'
}).addClass('animated slideInRight animate-duration-100');
}, 1000);
setTimeout(function () {
$('.itemTwo').css({
'background-color': 'rgba(0, 27, 53, 0.8)',
});
}, 1200);
setTimeout(function () {
$('.itemThree').css({
'background-color': 'rgba(136, 211, 192, 0.25)',
});
}, 1200);
将这些链接起来的最好方法是使用 promise 链来使代码紧凑和整洁吗?还是有别的办法?
最佳答案
不确定这是否是您想要的。我创建了一个工厂来包装您的逻辑,并在所有 promise 解决后触发回调。如果您需要进一步的帮助,请告诉我!干杯!
function createCssPromise($target, styleObj, timeout) {
const { newStyle, newClass } = styleObj;
return new Promise((resolve) => {
setTimeout(() => {
if (newStyle) {
$target.css(newStyle);
}
if (newClass) {
$target.addClass(newClass);
}
resolve();
}, timeout);
});
}
const targetObj = $('.itemOne');
const styleObj = {
newStyle: { 'visibility': 'visible'},
newClass: 'animated slideInRight animate-duration-100',
};
const timeout = 1000;
const firstPromise = new createCssPromise(targetObj, styleObj, timeout);
const secondPromise... //follow the pattern
const thirdPromise... // follow the pattern
Promise.all([firstPromise, secondPromise, thirdPromise]
.then(() => console.log('done!'));
*<= IE11 本身不支持 Promise.all。
关于javascript - 如何使用 promise 链接多个 setTimeout 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51742640/