利用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 + '%';
      }
    })();

不唯有与他人告别
24 声望4 粉丝

不唯有与他人告别