2

Short story I want to change an image every 4 seconds from an array of images. What do I need to add here to make this happen.

var list = ["img1", "img2", "img3"];

function ChangeBackground () {
  document.getElementById('background').src = "images/"+list[i];
}

window.setInterval(ChangeBackground(), 4000);

3 Answers 3

4

You could use a closure over the index.

function changeBackground() {
    var i = 0,
        imgURL = 'http://lorempixel.com/250/200/abstract/';
    return function () {
        document.getElementById('background').src = imgURL + list[i++];
        i %= list.length; // prevent looping over the length
    };
}

var list = [3, 1, 4, 7];

setInterval(changeBackground(), 4000);
//                          ^^         with brackets for returning function 
<img id="background">

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

Comments

0

Try:

var list = ["img1", "img2", "img3"];
var i=0;
function ChangeBackground () {
   i++;
   if(i>list.length-1){
       i=0;
   }
   document.getElementById('background').src = "images/"+list[i];
}

window.setInterval(ChangeBackground(), 4000);

Note that this does pollute the namespace.

Comments

0
var list = ["img1", "img2", "img3"],
    i = 0;                                                            // declare and initialize i outside of the function

function ChangeBackground () {
    document.getElementById('background').src = "images/" + list[i];
    i = (i + 1) % list.length;                                        // increment i after each call to this function (make sure i come back to 0 if it exceeds the length of the array using the modulo % operator)
}

window.setInterval(ChangeBackground, 4000);                           // pass a reference to the function not its return value (notice there is no parens after the function name)

1 Comment

Thank you! This answered everything I wanted to know ^^

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.