Becky
Becky

Reputation: 5585

1 second gap within each() function

I need to execute a function inside a each() function every 1 second. How can I do this?

$('.items:visible').each(function(){
    var id = this.id;
    executeNow(i, s, id);
    count++;
    if(count==total){
       ///do something
    }
});

Basically I need to have a 1 second gap each time the executeNow(); is called inside this each() function.

Upvotes: 3

Views: 182

Answers (4)

guest271314
guest271314

Reputation: 1

You can use .queue(), $.map(), .promise()

var colors = ["blue", "green", "red"];

function executeNow(el, args, next) {
  el.css("color", args)
  setTimeout(next, 1000)
}

function queueComplete(elems) {
  console.log(elems);
  alert("complete");
}

var items = $(".items:visible")

items.queue("items", $.map(items, function(item, index) {
  return function(next) {
    executeNow($(item), colors[index], next);
  }
}))
.dequeue("items").promise("items")
.then(queueComplete)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
  </script>
<div class="items">a</div>
<div class="items">b</div>
<div class="items">c</div>

Upvotes: 0

Rayon
Rayon

Reputation: 36609

First argument in jQuery.each is index which could be used as multiplication factor for setTimeout duration

$('.items:visible').each(function(index) {
  setTimeout(executeNow, 1000 * (index + 1));
});

As index for first iteration will be 0, index + 1 is used!

To pass arguments while invoking executeNow,

$('.items:visible').each(function(index) {
  setTimeout(function() {
    executeNow(args....);
  }, 1000 * (index + 1));
});

Upvotes: 3

jAndy
jAndy

Reputation: 235962

You can write a simple run-away-timer yourself, like so:

var set = $('.items:visible').get();

(function loop( elem ) {
    executeNow( elem );

    if( set.length ) {
        setTimeout( function() {
            loop( set.shift() );
        }, 1000 );
    }
}( set.shift() ));

That way, timers cannot interfere or overlap. Classical you would just call a setTimeout with increasing timeout values, but the solution above is cleaner and more reliable.

Upvotes: 6

gurvinder372
gurvinder372

Reputation: 68383

try this simple approach

var ms = 1000;
var runningMS = 0;
$('.items:visible').each(function(){
    setTimeout( function(){
        executeNow();
    }, runningMS );
    runningMS += ms;
});

Upvotes: 0

Related Questions