在Javascript中延迟显示多个图像

问题描述 投票:0回答:1

目的是每2秒钟后以循环顺序重复图像。我创建了2个函数,循环和随机,其中在循环中,图像旋转太快并被卡住,好像没有以循环顺序重复自身。而在随机功能中,它可以正常工作,但每2秒保持显示一次随机图像。

<script>
    var asgnimage = ["pic2.jpg","pic3.jpg", "pic1.jpg", "pic4.jpg"];
     function cycle(){
        for (i=0; i<asgnimage.length; i++){
            document.cb.src = asgnimage[i];
                    window.setTimeout("", 2000);
        }
        window.setTimeout ("cycle()",2000);
    }

    function rndm(){
        var randomIndex = Math.floor(Math.random(randomIndex) * 4)

            document.rm.src = asgnimage[randomIndex];

            setTimeout ("rndm()",2000);
        }

</script>
javascript arrays
1个回答
0
投票

您实际上只需要一个setTimeout一遍又一遍地调用函数-不需要for/loop。您可以为setTimeout提供其他参数,使其在调用时可以传递给函数-这就是我将在此处使用的参数:

const asgnimage = ["https://dummyimage.com/100x100/000/fff.png", "https://dummyimage.com/100x100/aa4cc3/fff.png", "https://dummyimage.com/100x100/556476/fff.png", "https://dummyimage.com/100x100/563765/fff.png"];

// Default index to 0
function cycle(index = 0) {

  // Set your image
  document.querySelector('#cb').src = asgnimage[index];

  // If you reach the end of the array set index to zero
  // otherwise increment it
  let nextIndex = index === asgnimage.length - 1 ? 0 : ++index;

  // Call `cycle` again passing in the new `index`
  setTimeout(cycle, 2000, nextIndex);
}

cycle();
<img id="cb" />
© www.soinside.com 2019 - 2024. All rights reserved.