Brob
Brob

Reputation: 675

jQuery delaying an each loop and trigger

I'm using the following code to delay a trigger looping through a list of li items

var eleID = '';
$('.SlideSelect').each(function(i) {  

    eleID = $(this).attr('id');

    $('#'+eleID).delay(800*i).trigger('click');
});

However the delay does not work and just loops through.

Does anyone know why?

var eleID = '';
$('.SlideSelect').each(function() {  

    eleID = $(this).attr('id');

    setTimeout(function(){
        $('#'+eleID).trigger('click');
    }, 5000)
});

Upvotes: 2

Views: 3161

Answers (5)

jAndy
jAndy

Reputation: 236122

Only fx methods do have an implicit impact on jQuerys internal queue. To have any other kind of method you explicitly need to call .queue():

$('#'+eleID).delay(800*i).queue(function( next ) {
    $(this).trigger('click');
    next();
});

This should work. The only thing I'm not so sure about is if this points to the jQuery wrapped set of invocation. I leave it to you to find out right now.

Another problem which comes along with this solution are the closures of ECMAscript. Since you're going to call that code within a loop, all those anonymous function(-contexts) will close over the eleID variable and reference it. To fix that, we need to invoke another context:

$('#'+eleID).delay(800*i).queue((function( myID ) {
    return function( next ) {
       $('#'+myID).trigger('click');
        next();
    };
}(eleID)));

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318618

You cannot use delay() for that since it only works for effects.

$('.SlideSelect').each(function(i) {  
    window.setTimeout(function() {
        $('#'+this.id).trigger('click');
    }, 800*i)
});

Upvotes: 0

jpea
jpea

Reputation: 3079

var eleID = '';
var i=0;
$('.SlideSelect').each(function(event) {  
   eleID = $(this).attr('id');
   $('#'+eleID).delay(800*i).trigger('click');
   i++;
});

Upvotes: -1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

.delay functions on effects (and you are trying to delay something other than an effect).

Admittedly, the documentation isn't obvious about this, beyond .delay being part of the Effects section.

Use setTimeout instead, in the usual fashion.

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532605

Delay is used for the animation queue. If you want to delay anything else, you should use setTimeout. Note the use of a separate function to allow the capture of each value in the delayed function.

var eleID = '';
$('.SlideSelect').each(function(i) {  

    eleID = $(this).attr('id');
    delayedTrigger( $('#'+eleID), 800*i );
});

function delayedTrigger(elem, delay)
{
    setTimeout( function() { $(elem).trigger('click'); }, delay );
}

Upvotes: 2

Related Questions