2017-09-08 87 views
0

我已经编写了一个JavaScript程序,用于更改标题上的图片,等待,然后显示下一个。为什么不这样循环?

我都试过,当它到达的最后一张照片,使之循环圆背1,但它不工作,电脑总是死机,我真的卡住。

后来这将有选择褪色,并有不同的过渡,但现在,我甚至无法获得的功能永远循环下去,没有崩溃的电脑。

任何人都可以提供解决方案吗?

谢谢

安德鲁

var $initialDelay = 0; 
var $delay = 200; 
var $picture = 1; 
var $pictureAmount = 4; 

function myFunction() { 
    //first picture loaded in CSS 
    //loop through pictures 
    for (i=0;i<$pictureAmount;i++) { 
     setTimeout(function(){ 
      document.getElementById("header").style.backgroundImage = "url(img/slideshow/slideshow"+$picture+".jpg)"; 
      $picture++; 
     }, $initialDelay); 
     $initialDelay += $delay; 
    } 
} 
myFunction(); 
+1

使用[模](https://en.wikipedia.org/wiki/Modulo_operation)(''%)。 – Aaron

+0

为什么你的代码如此充满空白行? –

+0

'我试图使它循环轮回1时到达最后picture'在哪里? –

回答

0

这里是一个循环超过4个图像以超时的例子。我认为你应该能够在你的代码中使用它来做你想做的事情。

const 
 
    delayBetweenPictures = 1000, 
 
    numberOfPictures = 4, 
 
    initialPicture = 1, 
 
    image = document.getElementById('slideshow'); 
 
    
 
    
 
function changeToPicture(pictureIndex) { 
 
    console.log(`Changing picture to index ${pictureIndex}`); 
 
    // Change the image 
 
    image.src = `http://lorempixel.com/320/200/cats/${pictureIndex}`; 
 
    
 
    // Use a modulo operator to turn 4 (number of pictures) back to 0 and add 1 so the range becomes 1...number of pictures. 
 
    pictureIndex = (pictureIndex % numberOfPictures) + 1; 
 
    
 
    // Set a timeout of X ms after which the changeToPicture method is called again, this time with the new value of pictureIndex. 
 
    setTimeout((newIndex) => changeToPicture(newIndex), delayBetweenPictures, [pictureIndex]); 
 
} 
 

 
changeToPicture(initialPicture);
<img id="slideshow">

0

如果你想这对连续改变图片每200ms

var delay = 200; 
var picture = 1; 
var pictureAmount = 4; 

function myFunction() { 
    setTimeout(function() { 
     document.getElementById("header").style.backgroundImage = "url(img/slideshow/slideshow" + picture + ".jpg)"; 
     picture = (picture % pictureAmount) + 1; 
     myFunction(); 
    }, delay); 
} 
myFunction(); 
+0

这是完美的!非常感谢你!^_ ^ – aerotortoise

0

通过使用模运算就可以值之间循环1〜4个遍。

这将是更容易,如果你的图片是 “0索引”:

for (i=0; /* infinite loop */; i=(i+1)%$pictureAmount) { 
    // loops through 0, 1, ..., $pictureAmount - 1 
} 

,但可以为1索引的迭代进行调整:

for (i=1; /* infinite loop */; i=(i%$pictureAmount)+1) { 
    // loops through 1, 2, ..., $pictureAmount 
} 

例反复在1〜9:

function sleep(ms) { 
 
    return new Promise(resolve => setTimeout(resolve, ms)); 
 
} 
 

 
async function loop() { 
 
    for (i=1; /* infinite loop */; i=(i%9)+1) { 
 
    document.getElementById("view").innerHTML=i; 
 
    await sleep(1000); 
 
    } 
 
} 
 

 
loop();
<p id="view"></p>