1

How to set interval or may be timeout through the array, to produce effects for the element every 2 sec for example the 1-st idea is to programm something like this:

for (photoKey in arrBigPhotoes) {
      setInterval(function() {
        // alert(arrBigPhotoes[photoKey]);

          document.getElementById("big_photo").src='/upload/images/'+arrBigPhotoes[photoKey];

      }, 2000);
}

But it didn't work properly. May be someone can help me with this task I'll be extremely glad. I'm also have a jQuery - the resolution may be through this library, but without any plug-ins. Thanks.

1
  • Could you clarify what you mean by "didn't work properly"? Does everything gets assigned the same photo? Commented Jul 10, 2011 at 20:17

2 Answers 2

3

Try something like this -

var photos = ['1.jpg', '2.jpg', '3.jpg'];
var photo_index = 0;

function switchPhoto() {
  photo_index = (photo_index + 1) % photos.length;
  document.getElementById('big_photo').setAttribute('src', '/upload/images/' + photos[photo_index]);
}

setInterval(switchPhoto, 2000);

You should probably put this inside some kind of document ready event handler

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah the Math mechanizm photo_index = (photo_index + 1) % photos.length; is great thanks, also I've added only setInterval(switchPhoto, 2000); in document.ready statement - works perfect. And I wonder why are U using setAttribute except src?
Just habit - I don't remember exactly why I started using it, but I believe I ran into a situation at some point where directly accessing attributes didn't work, so I just always use setAttribute for consistency.
1

I would suggest you pre-load the images you are trying to display. If the user is on a slow connection, your approach would fail.

var images = new Array();
var counter = 0;

var image = document.createElement("img");
image.onload = function() {
    counter++;
};
image.src = <url>;
images.push(image);

The counter is there so that you can determine when all images are properly loaded. Let's say you have six images, then, in your "intervaled" function, you would immediately return if counter < 6.

Your "switcher" function could look this way

var i = 0;

setInterval(function() {
    if (counter < 6) return;

    i = (i+1) % images.length;
    document.getElementById("big_photo").src = images[i].src;
}, 2000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.