Reputation: 3085
I've written a small script that loops through a set of buttons each of which is assigned a function. Script is below:
$('#play').bind('click', function() {
setTimeout( function(){ $('#b12').click(); }, 0 );
setTimeout( function(){ $('#b13').click(); }, 2500 );
setTimeout( function(){ $('#b14').click(); }, 5000 );
});
Now this works fine but I'm trying to make it a little more automated than just calling each function with the `setTimeout'. I've got the code below but I think I'm doing something wrong:
$('#play').click(function(){
$('.buttons').each(function(){
var time = 0;
setTimeout( function(){ $(this).click(); }, time );
time+= 2500;
});
});
Here is the HTML in question:
<button id="b12" class="buttons" onclick="oct12()">12th</button>
<button id="b13" class="buttons" onclick="oct13()">13th</button>
<button id="b14" class="buttons" onclick="oct14()">14th</button>
<button id="play">play</button>
Upvotes: 0
Views: 123
Reputation: 1123
You can use the index of .each for this, in ur own code u resetted time every iteration
$('#play').click(function(){
$('.buttons').each(function(i){
setTimeout( function(){ $(this).click(); }, i * 2500);
});
});
Upvotes: 2
Reputation: 185
You may use something like the plugin jquery-timing. This makes timing issues very easy:
$('#play').bind('click').$('#b12,#b13,#b14').each($).click().wait(2500);
That's it.
This example uses the plugin's inline version of bind(), the sequentially looped version of each(), and the deferring method wait(timeout).
PS: I like to write .on('click') instead of .bind('click') because it reads more fluently like a sentence.
Upvotes: 0
Reputation: 28705
put you time
variable outside .each() like code bellow:
$('#play').click(function(){
var time = 0;
$('.buttons').each(
setTimeout( function(){ $(this).click(); }, time );
time+= 2500;
});
});
Upvotes: 1