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

时间:2012-08-14 01:18:21

标签: javascript loops increment

我想将图像更改为图像“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);
    }
  };

这涵盖了 i&lt;时所需要做的事情。 n ,那么当 i 不小于 n

时,如何告诉它该怎么做?

4 个答案:

答案 0 :(得分:1)

使用全球imgIndex

imgIndex = 0;
noOfImages = 10;

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

请在下次让您的问题更清晰。

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

答案 3 :(得分:0)

当i&gt; = 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)
    }
}

我假设这个答案你的Interval就是你想要回忆这个函数的方法......这里的另一个答案显示使用while(1)循环和你的另一个循环内部的方法来循环遍历而不是计时器

相关问题