运行循环,然后重置并再次运行它

run through a loop and then reset and run it again

本文关键字:运行 循环 然后      更新时间:2023-09-26

我想将图像更改为图像"i",直到用完图像为止,然后我想从头开始。

这是我需要做的

  • 运行以下代码,直到 i>= n
  • 然后将 i 重置为零

法典:

  function advanceSlide()
  {
    i++;
    currentIMG ='"image"+i';
    changeBG(currentIMG);
  }

这就是我到目前为止所拥有的,我只是在循环完成后休息 i 感到困惑:

  window.setInterval(function(){
    advanceSlide();
    }, 5000);
  function advanceSlide(){
    while (i<n){
      i++;
      currentIMG='"Image"+i';
      changeBG(currentIMG);
    }
  };

这涵盖了我<</em> n 时需要做什么,那么当我不小于 n 时,我如何告诉它该做什么

使用全局imgIndex

imgIndex = 0;
noOfImages = 10;
function advanceSlide(){
  imgIndex++;
  if( imgIndex >= noOfImages ) { imgIndex = 0; }
  currentIMG = "Image" + imgIndex;
  changeBG(currentIMG);
}

不需要将advanceSlide包装在函数中。您可以使用模数来重置i

window.setInterval(advanceSlide, 5000);
function advanceSlide(){    
    i = (i+1)%n;
    currentIMG="Image"+i;
    changeBG(currentIMG);   
}

下次请把你的问题说得更清楚。

int i = 0;
while (true){
        i++;
        if (i<n){
           currentIMG='"Image"+i';
           changeBG(currentIMG);
        }
        else
        {
           i = 0;
        }
}

当我>= n 时,它将简单地退出循环并继续您在 while() { } 之后输入的任何代码

使用您设置的间隔,不需要闭包,因为它只调用另一个函数,可以简化为window.setInterval(advanceSlide, 5000);

你也可以用 for 循环替换它 while 循环,因为你只是递增索引

window.setInterval(advanceSlide, 5000);
function advanceSlide() {
    for(i = 0; i < n; i++) {
        // also here don't really need to store in a variable just pass straight in
        changeBG("Image" + i)
    }
}

我假设这个答案是您的间隔是您想要回忆函数的方式...... 这里的另一个答案是使用 while(1) 循环和另一个循环,以便在没有计时器的情况下一遍又一遍地循环