views:

77

answers:

1

Hello,

I've just spent a long time trying to figure out why my Javascript for() loop won't work in a Drupal block, I feel like I've checked out the syntax - any idea why this isn't working?!

$(document).ready(function() {
var i=0;
while (i<=5)
  {
 alert(i);
  i++;
}
});

That doesn't do anything - and also if I put something like this in- does not work either:

for (var i=0; i<31; i++){
alert(i);
}

Thanks!

+3  A: 

None of the alerts will happen until the thread is done executing. By that time, i has exceeded your limit. This is a very commonly asked question. You need to learn about closures in JavaScript.

Here's a good overview. There are also many answers to this question in StackOverflow.

http://james.padolsey.com/javascript/closures-in-javascript/

From that article, this code:

for (var i = 0; i < 100; ++i) {
    myElements[i].onclick = (function(n) {
        return function() {
            alert( 'You clicked on: ' + n );
        };
    })(i);
}

Which is similar to what you want.

Nosredna
Thank you. That makes sense.
Bloopy
Doesn't alert block the execution? I don't think this has got anything to do with closures - the code in the question isn't attaching event handlers in a loop.
Chetan Sastry
Hmm. You may be right. I'm going to delete and think about this. alert should block.
Nosredna
Arggh. I can't delete because it's accepted.
Nosredna