简体   繁体   中英

why does statement below loop executes before termination of loop

I was wondering why do i get alert before printing all vlaues

<script>
    for(var i=0; i<=1000; i++)
    {
        console.log(i);
    }
    alert('Hello');
</script>

Well it is not executing before loop, it is executing correctly.

Your console may be refreshing little late.

alert() will block your browser whilst waiting to be dismissed by the user .

Maybe they haven't been written to the console yet by the time the alert appears. It depends on what your console object is.

BTW, they appear fine in the console before the alert in my Chrome 10 on OS X.

The console is lagging behind. The loop is executed first. This shows it better:

var t = [];
for(var i=0; i<=1000; i++)
{
    t.push(i);
}
console.log(t.length);
alert('Hello');

How are you executing this? My console doesn't show the alert until all the numbers are displayed. Yours must be lazily rendering output. So the loop does finish before the alert, but the log was only written to a buffer.

<script>
INSTRUCTION A;
INSTRUCTION B;
INSTRUCTION C;
</script>

In javascript the execution of INSTRUCTION B is not dependent upon completion of A and similarly for C.

You may want to try something like:

var test = 0;
var i=0;
while(test!=1) {
  console.log(i);
  i++;
  if(i==1000) {
    alert("Hi!");
    test=1;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM