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)
}
});
Increase your delay by 2 seconds per iteration.
setTimeout is non-blocking, so code will continue to run before the delay has passed, resulting in you firing off x setTimeout’s all at the same time with the same delay, so they all finish at the same time.