Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Repeating jQuery Each Behavior

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)
        }
      });
like image 899
user1114864 Avatar asked Jun 27 '26 21:06

user1114864


1 Answers

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

like image 194
Denys Séguret Avatar answered Jun 29 '26 12:06

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!