-1

Possible Duplicate:
Show and hide divs at a specific time interval using jQuery

I have a jQuery script what is showing and hiding divs at a specific interval. It's working fine but I have one problem, its showing and hiding divs round and round so basically its never stops. How can I make this stop? Lets say it stops after showing 3x the divs.

$(function() {
    var timer = setInterval( showDiv, 5000);    
    var counter = 0;

    function showDiv() {
        if (counter == 0) { 
            counter++; 
            return; 
        }

        $('div','#container')
            .stop()
            .hide()
            .filter( function() { return this.id.match('div' + counter); })   
            .show('fast');

        counter == 3? counter = 0 : counter++; 
    }
});
Community
  • 1
  • 1
nmsdvid
  • 2,832
  • 2
  • 21
  • 21
  • See http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript – Stefan Nov 25 '11 at 14:04
  • 2
    Seems like you copy-pasted some code from this page: http://stackoverflow.com/q/915016/508702 and now wonder why it is not working? – Bas Slagter Nov 25 '11 at 14:05

4 Answers4

2

Use setTimeout() and clearTimeout() instead of setInterval().

JMax
  • 26,109
  • 12
  • 69
  • 88
Hazza
  • 6,441
  • 3
  • 24
  • 37
1

Try this:

$(function() {

  var timer = setInterval( showDiv, 5000);

  var counter = 0;
  var showTimes = 3;
  function showDiv() {
    if (counter ==0) { counter++; return; }

    $('div','#container')
      .stop()
      .hide()
      .filter( function() { return this.id.match('div' + counter); })   
      .show('fast');

    if(counter == 3){
       counter = 0;
       showTimes--;
       if(showTimes == 0)
           clearInterval(timer);
    }else{
       counter++; 
    }

  }

});
Niels
  • 48,601
  • 4
  • 62
  • 81
0

add your whole code into a function and call that function within a for loop only thrice with the time interval

yrk
  • 67
  • 3
  • 10
0

You can use setInterval as you are using it now. When you want the timer to stop you call clearInterval, passing it the timer you got from the setInterval call. You can do this inside your showDiv function if you like.

Mike E
  • 5,493
  • 1
  • 14
  • 15