Question

I'm trying to execute a rotating banner (Calling it through an array). I set an interval but the image only shows after 10 seconds (10000) and only then begins the rotation. I removed the cluttered HTML of the array, but here's the rest of it:

var current = 0; 

var banners = new Array();
banners[0]=;
banners[1]=;
banners[2]=;
banners[3]=;

var myTimeout = setInterval("rotater()",10000);

function rotater() {
    document.getElementById("placeholderlayer").innerHTML=banners[current];
    if(current==banners.length-1){  
        current = 1;
    }else{
        current += 1;
    }
 }

window.onload = rotater();
Was it helpful?

Solution

window.onload = rotater;

is the correct syntax. You don't want to call the function. However, the bulletproof solution is rather this:

onload = function() {
    rotater();
    window.myTimeout = setInterval(rotater, 10000); // Never pass a string to `setInterval`.
};

ProTip™: Don't use new Array(), use an array literal. For example, this:

var arr = new Array();
arr[0] = 'Hello';
arr[1] = 'world!';

Should be written as:

var arr = ['Hello', 'world!'];

OTHER TIPS

Just a comment:

Instead of:

if(current==banners.length-1) {
   current = 1; 

} else {
   current += 1;
} 

you can do:

current = ++current % banners.length;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top