2012-08-14 146 views
0

我想将图像更改为图像“i”,直到图像用完,然后我想从头开始。运行一个循环,然后重置并再次运行它

这是我需要做的

  • 运行下面的代码,直到我> = N
  • 然后复位I为零

代码:

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

这是我到目前为止,我只是休息当循环完成:

window.setInterval(function(){ 
    advanceSlide(); 
    }, 5000); 

    function advanceSlide(){ 
    while (i<n){ 
     i++; 
     currentIMG='"Image"+i'; 
     changeBG(currentIMG); 
    } 
    }; 

这涵盖了什么,我需要的时候我<ñ,让我怎么告诉它做什么,当不小于ň

回答

1

使用更清晰的未来添了全球imgIndex

imgIndex = 0; 
noOfImages = 10; 

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

完美。谢谢,这就是我需要的。 – 2012-08-14 01:40:05

0

请你的问题即

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

当我> = N,则它会简单地退出循环,并继续与你的同时(后放置任何代码){}

与你设定的时间间隔,没有必要为一个封闭有因为它只有一个调用其他功能,可以简化为window.setInterval(advanceSlide, 5000);

你也可以更换while循环与for循环,因为你只是增加一个索引

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)循环与你的另一个循环内部的方式来循环一遍又一遍,没有计时器

1

你不需要在功能中包装advanceSlide。你可以使用模数得到重置我

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

作出了upvote,因为即使其他被接受,这也是最好的答案。现在我删除了我的意见,所以不要混淆任何其他人在未来发现此Q ...对不起 – 2012-08-14 03:38:26

相关问题