为什么不循环呢?

时间:2017-09-08 10:08:52

标签: javascript loops

我编写了一个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();

3 个答案:

答案 0 :(得分: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">

答案 1 :(得分:0)

如果您希望每隔200毫秒连续更换图片

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();

答案 2 :(得分: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>