1

I am trying to roll through my banner images using a while loop in jQuery.

I need to find a way to pause each cycle of the loop so the banner images can cycle round slowly.

Here is my code

var bannerIMG = ['img1','img2','img3'];
var counter = 0;
var num = 1;
while (num <= 3) {
$('#header').addClass(bannerIMG[counter]);
   counter = counter +1;    
   num = num+1;
}

Thanks in advance

4
  • Can you show a fiddle? Commented Apr 5, 2013 at 21:50
  • 4
    A setInterval or setTimeout would be more appropriate Commented Apr 5, 2013 at 21:50
  • @roXon is right, or if you need more you can use deferred functions (see the jQuery Promise object) and a setTimeout that goes to the next function in the list. Commented Apr 5, 2013 at 21:51
  • jquery4u.com/jquery-functions/setinterval-example Commented Apr 5, 2013 at 21:52

2 Answers 2

3

LIVE DEMO

var img = ['img1', 'img2', 'img3'],
    c = 0,
    run = setInterval(loop, 1000); 

function loop(){ 
  $('#header').removeClass().addClass( img[++c%img.length] );    
}

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Arithmetic_Operators/
http://api.jquery.com/

Sign up to request clarification or add additional context in comments.

1 Comment

@GeorgeShikariReason You're welcome! well, I changed a bit my code since last time ;)
-2

Got it working with this code

var bannerIMG = ['img1','img2','img3'];
var counter = 0;
function loop(){
    $('#header').addClass(bannerIMG[counter]);
    counter = counter+1;
}

setInterval(loop, 1000);

Thanks for the help everyone

1 Comment

with +=1, it'll fail once it gets to the 4th image (since it doesn't exist in the array)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.