dedronek
dedronek

Reputation: 61

setTimeout() work only 2 times

this is my code

<script type="text/javascript">
window.onload=change;
var i=0 ;
function change()
{
    var images = new Array('1','2','3','4','5','6');
    document.getElementById('baner').src = obrazy[i];
    i++
    if (i == images.length)
    {
        i=0;
    }
}
setTimeout(change,1000);
</script>

I want make simple slider but setTimeout do my script only 2 times. Yes, I have element with id baner. I dont know what is wrong with that.

Upvotes: 1

Views: 768

Answers (2)

GibboK
GibboK

Reputation: 73908

You should use the setInterval() method which calls a function or evaluates an expression at specified intervals (in milliseconds).

window.onload=change;
var i=0 ;
function change()
{
    var images = new Array('1','2','3','4','5','6');
    document.getElementById('baner').src = obrazy[i];
    i++
    if (i == images.length)
    {
        i=0;
    }
}
setInterval(change,1000);

setTimeout() method calls a function after a specified number of milliseconds and stop.

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42460

You are calling change only twice, once in the handler of window.onload, and once after a timeout of 1 second.

You may be looking for setInterval instead of setTimeout:

window.onload = function() {
    var i=0 ;
    function change() {
        var images = new Array('1','2','3','4','5','6');
        document.getElementById('baner').src = obrazy[i];
        i++;
        if (i == images.length) {
            i=0;
        }
    }
    setInterval(change,1000);
    change();
}

Upvotes: 4

Related Questions