【问题标题】:How do I use setTimeout or setInterval while iterating over an array?遍历数组时如何使用 setTimeout 或 setInterval?
【发布时间】:2019-06-01 23:12:56
【问题描述】:

我需要不断迭代一个数组(其中实际上包含用于生成 Canvax 图像的 id)。

所以我需要一遍又一遍地迭代键数组,并延迟设置 id。

function animateCanvas() {
    keys = getKeys();
    let offset = 0;
    keys.forEach(function(key){
        setTimeout(function(){
            animateFrame(key);
        }, 2000 + offset);
        offset += 2000;
        keys = [];
    });
}


function animateFrame(id) {
    const animationCanvas = document.querySelector(`.canvas-animation`);
    const animationContext = animationCanvas.getContext('2d');
    const canvas1 = document.getElementById(id);
    animationContext.clearRect(0, 0, animationCanvas.width, animationCanvas.height);
    animationContext.drawImage(canvas1, 0,0, 170, 170, 0, 0 , 150, 150);
}

预期结果将是通过 animateFrame(key) 将另一个图像无限设置到画布,延迟 2 秒

【问题讨论】:

  • 我会使用一个普通的 for 循环并在达到 length 时重置迭代器。 forEach 设置要在开始时访问的元素,并且不会重新访问元素。

标签: javascript arrays iteration settimeout setinterval


【解决方案1】:

这种方法行不通,因为您希望不断地迭代图像。我会建议用户 setInterval 。

试试下面的代码

// This is your array of images
var x = [1, 2, 3, 4];

// This is your canvas displaying function
function something(x) {console.log(x)}

setInterval(() => {
  // It checks if we have reached the end
  if(curr == x.length - 1)
    curr = 0;

  something(x[curr]);
  curr++;
}, 2000)

【讨论】:

    【解决方案2】:

    您是否考虑过使用.requestAnimationFrame() 而不是循环?它实际上非常适合您的用例。

    这就是它的样子。请注意有关将图像添加到画布的位置的注释。

    const data = ["<div></div>", "<section></section>", "<article></article>"];
    // Set delay to 5000 for 5 seconds
    const delay = 2000;
    // set previousCall to 1 to wait for first or -(delay) to start immediately 
    let previousCall = -(delay);
    
    function animateCanvas(now) {
      if (now - previousCall >= delay) {
        // grab data from array in some fashion
        let id = parseInt(now/3 % 3);
        animateFrame(id);
        previousCall = now;
      }
      requestAnimationFrame(animateCanvas);
    }
    requestAnimationFrame(animateCanvas);
    
    function animateFrame(id) {
        document.body.innerHTML += data[id];
    }
    div, section, article {
      width: 50px;
      height: 50px;
      background-color: blue;
      margin: 3px;
    }
    div {
      background-color: blue;
    
    }
    section {
      background-color: yellow;
    
    }
    article {
      background-color: orange;
    
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    
    <body>
    </body>
    
    </html>

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多