Lbh
Lbh

Reputation: 67

jQuery - Create x elements, one after the other

I use Jquery UI to drag'n'drop an element 'spider' in an element 'attic'

$('.animaux').draggable( {
  containment: '.page',
  stack: '.menu_animaux img',
  cursor: '-webkit-grab',
  revert: 'invalid',
  helper: 'clone'     
});

$('#grenier').droppable( {
  accept: '.l_grenier',
  hoverClass: 'hovered',
  drop: grenierDrop      
});

The spider's drop call a function 'grenierDrop' that creates a new spider in a random position, in the attic :

$('<img class="araignee" src="img/araignee.png" />').css({
        'position':'absolute',
        'top': (Math.random() * ($('#grenier').height() - $('.araignee').height())).toFixed()+'px',
        'left': (Math.random() * ($('#grenier').width() - $('.araignee').width())).toFixed()+'px'
        }).appendTo('#grenier').addClass("animated tada");

i Want to repeat this function 10 times, with a delay between each one. I know how to create 10 spiders at the same time (using FOR loop), but not how to create them one after the other, with by example a 2 seconds delay (i tried setTimeout, setInterval, FOR loop, but without any result).

I think it's a basic issue, but i am a beginner... Thx for you help

Upvotes: 1

Views: 102

Answers (1)

Magus
Magus

Reputation: 15104

setInterval is the key to do that.

var counter = 0;

var timer = setInterval(function() {
    // Do some stuff

    counter += 1;
    if (counter >= 10) {
        // Kill the timer after 10 times
        clearInterval(timer);
    }

}, 2000 /* In ms. So it's 2 seconds */);

Upvotes: 1

Related Questions