Tara O'Shea
Tara O'Shea

Reputation: 39

Run function x amount of times

Im trying to make a div appear every 30 seconds, but for only 5 times. The code I have works fine, just loops through divs and shows a div every 30 seconds, but i need it to stop after it has done this 5 times.

  $(window).bind("load", function flashing() {
  var counter = 0,
  divs = $('.flash-image');
    function showDiv () {
        divs.hide() // hide all divs
        .filter(function (index) { return index == counter % 30; })
        .show('fast'); 
        counter++;
    };

    showDiv(); // show first div    
    setInterval(function () {
        showDiv(); // show next div
    }, 1 * 1000); // do this every 1 seconds 
});

Upvotes: 1

Views: 2147

Answers (2)

Instance Noodle
Instance Noodle

Reputation: 227

 $(window).bind("load", function flashing() {
  var counter = 0,
  divs = $('.flash-image');
    function showDiv () {
        divs.hide() // hide all divs
        .filter(function (index) { return index == counter % 30; })
        .show('fast'); 
        counter++;
    };

    showDiv(); // show first div    
    var inter = setInterval(function () {
        if(counter < 5){
          showDiv(); // show next div
        }else{
          clearInterval(inter);
        }
    }, 1 * 1000); // do this every 1 seconds 
});

Upvotes: 0

nicosantangelo
nicosantangelo

Reputation: 13716

var amount = 0;
var timerId = setInterval(function () {
    showDiv(); // show next div
    amount++;
    if(amount === 5) {
        clearInterval(timerId);
    }
}, 1 * 1000); // do this every 1 seconds 

Upvotes: 3

Related Questions