简体   繁体   中英

How do I use setTimeout or setInterval while iterating over an array?

I need to continuously iterate over an array (which actually contains ids used to generate canvax images).

So I need to iterate over the array of keys over and over again, with ids being set with a delay.

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);
}

Expected result would be endless setting another image to canvas via animateFrame(key) with a delay of 2 seconds

This approach won't work as you want to continuously iterate over images. I would suggest user setInterval for it.

try the below piece of code

// 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)

Have you considered using .requestAnimationFrame() rather than a loop? It is actually quite ideal for your use case.

This is what it would look like. Note the comment about where to add the image to the canvas.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM