1

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();
Teun Zengerink
  • 4,277
  • 5
  • 30
  • 32
Black Bird
  • 797
  • 1
  • 10
  • 34
  • Not your specific problem you are asking about, but an improvement worth noting. `setInterval` should be passed a direct function reference, not a string like this: var `myTimeout = setInterval(rotater, 10000);` – jfriend00 Jul 29 '12 at 23:59

2 Answers2

3
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!'];
Ry-
  • 218,210
  • 55
  • 464
  • 476
1

Just a comment:

Instead of:

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

} else {
   current += 1;
} 

you can do:

current = ++current % banners.length;
RobG
  • 142,382
  • 31
  • 172
  • 209