I am trying to loop through a couple of different values. The idea is that if a user clicks a button the loop should start to run, once it runs it should show a piece of code(in the example some basic text). I am trying to show a sort of dialog with different information, the duration depending on the time values(milliseconds), so the first starts with 3 seconds, right after that the second should be visible for 8 seconds, after this the last one should run for 2 second.
I had to make changes so that every loop the time is different. The example below has a kill switch, so that i can kill the loop. I hope that somebody can figure this out, I have tried a lot of hours and hours.
//plugin options
step:[
{
time: 3000,
name: 'mike',
age: 30
},
{
time: 8000,
name: 'john',
age: 37
},
{
time: 2000,
name: 'jessica',
age: 25
}
]
// the loop
var timeouts = [];
$('.click').click(function(){
$.each(options.step, function(i, value){
var time = value.time;
timeouts.push(setTimeout(function(){
$('#target ul').append('<li>'+value.name+'-'+value.age+'</li>')
},time));
});
});
// reset button
$('.stop').click(function(){
$.each(timeouts, function (_, id) {
clearTimeout(id);
});
timeouts = [];
});
EDIT: the issue is that it needs a extra value(0) in the loop(first value should be a 0), as the the first setTimeout runs after 3 seconds, which means that the rest will use the value of there neighbor.