利用 then 会期待上一个 Promise 的解决的个性来模仿一个申请 loading。
效果图
CSS
.div {
width: 0%;
padding: 10px 0;
background-color: violet;
text-align: center;
transition: width 1s;
}
JavaScript
function sleep(delay = 1000) {return new Promise((resolve, reject) => {
// 提早期待,模仿异步申请
setTimeout(() => {resolve();
}, delay);
});
}
(async function show() {
let args = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,];
let div = document.querySelector('.div');
for (let i = 0; i < args.length; i++) {await sleep();
// 获取进度,i=0 所以 +1 除以总长度 乘以 100
let progress = Math.round(((i + 1) / args.length) * 100);
// 赋值给元素的宽度和给渲染元素进度
div.style.width = progress + '%';
div.innerHTML = progress + '%';
}
})();