views:

64

answers:

3

I want an image to change every second. I'm having trouble with setInterval. Could someone post a quick snippet on how to do this

This is what I came up with.

var images = 'images/image_*.png';
for(var i = 1; i <= 5; i++){
    function changeImg(){
     var path = images.replace('*', i);
     $('img').attr('src', path);
    }
    setInterval('changeImg()', 1000);
}
+3  A: 

In your code you are calling the setInterval function 5 times which really is not necessary. Also as the loop will execute once, the value of i will always be 5 so it won't work as you expect. You may try this instead:

var images = 'images/image_*.png';
var i = 1;
setInterval(function() {
    var path = images.replace('*', i);
    $('img').attr('src', path);
    i = i + 1;
    if (i == 6) i = 1;
}, 1000);
Darin Dimitrov
I didn't know you could call anonymous functions to setInterval, thanks :)
Ben Shelock
@Darin, the only thing I would change is to move the `i = i + 1` call to just before the `if` statement, and change it so `i = 1`. Right now the code gives the initial impression of a zero indexed counter, when really the `0` value is always incremented once before use.
Doug Neiner
@dcneiner, agree with you. I've updated my answer.
Darin Dimitrov
Looks good @Darin. +1 for the anonymous function in the `setInterval` call.
Doug Neiner
A: 
var images = 'images/image_*.png';
var i = 1;
function changeImg(i){
    var path = images.replace('*', i);
    $('img').attr('src', path);
}

setInterval('changeImg('+ ( (i++)%6 ) +')', 1000);

Maybe something like this ? I didn't test it though.

Soufiane Hassou
I don't believe that will actually cycle because the current value of `i` will get encoded into the setInterval string.
Justin Love
+2  A: 

Your loop was still continuing without waiting. Try writing it this way:

var images = 'images/image_*.png',
    i      = 1;

function changeImg(){
    var path = images.replace('*', i);
    $('img').attr('src', path);
    i = (i == 5 ? 0 : i + 1);
}

window.setInterval(changeImg, 1000);
Doug Neiner
Most JS programmers I talk with now avoid passing a string to setInterval, so... window.setInterval(changeImg, 1000);
Nosredna
Thanks @Nosredna, I updated my example to reflect that. I appreciate the heads up!
Doug Neiner