Patrik Krehák
Patrik Krehák

Reputation: 2683

How can I run function for each element in different time?

I need to know, how can I run one function for each element I select. This is my jQuery code:

$(function() {
  $(".line").each(function() {
    var dot = $(this).find('.dot');
    setTimeout(function () {
      moveDot(dot);
    }, 250);
  });
});

It could run moveDot() for each element (every after 250ms), but now, all elements starts at the same time. Here is JSFIDDLE.

Upvotes: 0

Views: 59

Answers (5)

Sandeep Pal
Sandeep Pal

Reputation: 2175

I will prefer like this as one of solution:

 function moveDot(elm,index) {
  elm.animate({left: '370px'}, {duration: 3000*index, queue: false, done: function() {
  elm.animate({left: '0px'}, {duration: 3000*index, queue: false, done: function() {
  moveDot(elm,index)
    }});
  }}); 
 }

  $(function() {
   $(".line").each(function(i) {
   var dot = $(this).find('.dot');
   setTimeout(function () {
     moveDot(dot,++i);
   }, 250);
  });
  });

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20626

Try passing index to setTimeout(). It would increment for each element in the loop, and thus add to the delay.

$(function() {
  $(".line").each(function(index) {
    var dot = $(this).find('.dot');
    setTimeout(function () {
      moveDot(dot);
    }, index * 250);
  });
});

Fiddle

Upvotes: 2

tuan huynh
tuan huynh

Reputation: 727

You can use random function javascript

(function() {
  $(".line").each(function() {
    var x = Math.floor((Math.random() * 250) + 1);
    var dot = $(this).find('.dot');
    setTimeout(function () {
      moveDot(dot);
    }, x);
  });
});

Upvotes: 0

Sudharsan S
Sudharsan S

Reputation: 15393

Multiply with each index

$(".line").each(function(i) {
   var dot = $(this).find('.dot');
   setTimeout(function () {
     moveDot(dot);
   }, 250 * i+1);
});

DEMO

Upvotes: 2

Ram
Ram

Reputation: 144689

Use the indices:

$(".line").each(function(i) {
   var dot = $(this).find('.dot');
   setTimeout(function () {
     moveDot(dot);
   }, ++i * 250);
});

http://jsfiddle.net/d59c7/

Upvotes: 2

Related Questions