2017-09-08 116 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>