0
function call()
{
    var i=0,
        img=document.getElementById("img1");
    for(i=1;i<=3;i=i++)
    {
        setInterval(function(){
            img.src="Images/"+i+".jpg";
        },3000);

    }

}

There is nothing displayed on the webpage. The image names are correct. When the code is executed the computer hangs.

  • possible duplicate http://stackoverflow.com/questions/7749090/setinterval-within-for-in-loop – rob Jul 07 '14 at 07:37

2 Answers2

2
i=i++

This is not the correct use to increment i.

What this does:

  1. Variable i gets incremented by ++.
  2. Variable i gets assigned old value of i, as i++ returns the old value of i.

So basically, you are stuck in an endless loop. Just replace i=i++ with just i++ or i=i+1 or i+=1 and you should be fine.

Looking at your code again, I have to tell you, that this will still not yield the desired effect, as you are setting all the intervals to fire at the same exact time. What you would want to do looks something like this:

function next() {
    setInterval(function(){
        //display next image
    },3000);
    next();
}
next();

Depending on how your html-code is build, the simplest way to implement this would be:

var count = 3; current = 0, img=document.getElementById("img1");
function next() {
    setInterval(function(){
        current++;
        if(current >= count) {
            current = 0;
        }
        img.src="Images/" + current + ".jpg";
    },3000);
    next();
}
next();
Lars Ebert
  • 3,487
  • 2
  • 24
  • 46
0

With respect to your angle of code.. try the below one.

function call(){
            var i=0;
            setInterval(function(){
                    document.getElementById("pics").innerHTML="<img src='img"+i+".jpg' width=300 height=300 alt='image' /> ";
                i++;
                if(i>=3){
                    i= i%3;
                }
            },3000);
        }

"pics" is a div tag declared in html page.

practice2perfect
  • 499
  • 1
  • 4
  • 19