Javascript 和 Vue.js 异步函数替代中的无限 while 循环

Javascript and Vue.js infinite while loop in async function alternative

我目前使用异步函数从 DOM 中插入一组特定的元素,它目前工作得很好但是我无法通过例如 lint 验证所以我想知道是否有人知道更好的解决方案。这是我当前的代码:

 async mounted() {
    let colorMap = interpolate(['#fffbfb', '#ff4141']);

    let i

    // eslint-disable-next-line no-constant-condition
    while (true) {
      let switchColor = false
      for (i = 0; i < 100; i++) {
        let group = this.blinkingGroup
        if (!switchColor) {
          colorMap = interpolate(['#ff4141', '#fffbfb']);
        } else {
          colorMap = interpolate(['#fffbfb', '#ff4141']);
        }
        group.forEach(value => {
          try {
            value.dom.style.stroke = colorMap(i * 0.01)
          } catch (e) {
            //console.log(e)
          }
        })
        await new Promise(r => setTimeout(r, 10));
        switchColor = true

      }
    }
  }

更新:如评论中所述,requestAnimationFrame 更适合此处:

为什么更好?

  • 浏览器可以优化,动画会更流畅
  • 非活动选项卡中的动画将停止,让 CPU 冷静下来
  • 更省电

您可以阅读有关 RequestAnimationFrame 的更多信息here and here



你可以使用 setInterval 而不是 while(true)

setInterval(function, milliseconds)