NooBskie
NooBskie

Reputation: 3841

Inserting incremental values into loop array

Right now I am animating an image by stringing multiple images together with setInterval(showNextSlide, 100); and it works really well.

The only thing that I'm running into problems with is adding values dynamically into var slides = [src, ] the while loop just loads the final image.

Also the way the images are saved the increment moves to the next zero so 01009 converts to 01010 whenever I use my loop it will convert to 010010 note the extra zero at the end.

Javascript

window.onload = function() {
  var img = 0
  while (img < 15) {
    img++;
  }
  var src = 'assets/images/earth/Sequence%0100' + img + '.jpg.';
  var slides = [src, ],
    index = 0,
    timer = 0;

  // Show the first slide
  showNextSlide();

  // Show "next" slide every five seconds
  timer = setInterval(showNextSlide, 100);

  // The function we call to show the "next" slide    
  function showNextSlide() {
    if (index >= slides.length) {
      index = 0;
    }
    document.getElementById('earth').src = slides[index++];
  }
};

JsFiddle

Upvotes: 0

Views: 56

Answers (3)

Suchit kumar
Suchit kumar

Reputation: 11869

try this:It will keep on changing the image src of earth based on the index value.

Update based on JEES Comment.

<script>

  window.onload = function() {
       var i = 0

  var slides = [];
  while (i < 200) {

      if(i <= 9){ img= '0100' + i++; }
      else if(i <= 99){ img= '010' + i++; }  
      else{ img= '01' + i++; }  
      var src = 'assets/images/earth/Sequence%' + img + '.jpg';
      slides.push(src);    
    }

        console.log(slides);
        index = 0,
        timer = 0;

      // Show the first slide
      showNextSlide();

      // Show "next" slide every five seconds
      timer = setInterval(showNextSlide, 100);

      // The function we call to show the "next" slide    
      function showNextSlide() {
        if (index >= slides.length) {
          index = 0;
        }
        document.getElementById('earth').src = slides[index++];
      }
    };
</script>
<img src="" id="earth">

Upvotes: 1

Mi-Creativity
Mi-Creativity

Reputation: 9664

This is part of the answer and it will fix it when img value is 9 or 99 since he has 200 images, if images number > 1000 he'd need another one when img value 999.. please tell me if i should delete this answer:

UPDATED:

 var img = 0;
 while(img < 200) {
    if (img < 10) { imgURL = '0100' + img; }
    else if (img < 100) { imgURL = '010' + img;}
    else { imgURL = '01' + img; }
    slides.push('assets/images/earth/Sequence%' + imgURL + '.jpg');
    img++;
}

check this Fiddle to see it in action..

Upvotes: 0

Chilli
Chilli

Reputation: 123

Please Try It :

var img = 0;

var slides = new Array(); 

while (img < 5) {

img++;

var src = 'assets/images/earth/Sequence%0100' + img + '.jpg';

slides.push(src);

}

Upvotes: 1

Related Questions