Weird conceptual question. The array below contains three elements. When I run this code, my intention is that the script waits two seconds, shows an alert, waits two seconds, shows an alert, waits two seconds, and shows a final alert. Instead, it just waits two seconds, and then shows all three alerts back to back to back. I've been fooling around with it for a while, but can't find what I'm missing. Any suggestions?
$.each(node_array, function(index,value){
if(value != undefined){
setTimeout(function(){
alert("hey")},
2000)
}
});
When you iterate, you set the timeout but you don't stop the iteration. So all the setTimeout are launched at the same time.
What you need is to launch the next setTimeout after the user clicked the alert :
var i=0;
function onestep(){
alert('hey');
var value = node_array[i];
if (++i<node_array.length) setTimeout(onestep, 2000);
}
onestep();
Demonstration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With