I have written a bit of jQuery to loop through items in a array an display a random number and then move on to display another number. The problem is I want to put a delay inside the loop so that it shows the number for 2 seconds and then moves of to the next. so you see a random number it holds for 2 seconds and then moves on to the next. I have tried putting a timeout inside the loop but that didn’t work. Any help would be amazing thanks.
function RandomNumberGenerator(){
var myArray = new Array(99);
for (var i=0; i< 99; i++) {
myArray[i] = Math.floor(Math.random()*100)
myArrayTwo[i] = Math.floor(Math.random()*100)
}
for (var i=0; i< 9; i++) {
$('li.num').text(function(index) {
// timeout needs to be here somewhere
return (myArray[i]);
})
}
});
}
First of all you need to put the code that does the work (displays the random number and decides if it should continue) inside its own function. This function can also be a local variable inside
RandomNumberGenerator:The function above puts a number in
li.num, incrementsi, and tells the browser to call the function again (usingsetTimeout) in two seconds — but only if we have shown less than 100 numbers.So when this function (
displayNumber) is called for the first time, it displays one number and sets things up to call itself again after 2 seconds (to display another number, and so on). If it has displayed 100 numbers already it does not set the call up again, so at that point the repetition stops.So you can now do: