Infinite loop triggered by absence of alert()
For reasons entirely beyond my comprehension, this function runs just fine:
function foo() {
var loop = true;
var abc = ["a","b","c"];
var ctr = 0;
while(loop) {
$("<img />").error(function () {
loop = false;
}).attr('src','images/letters/'+abc[1]+(ctr++)+".jpg");
alert(ctr);
}
}
But movi开发者_如何学Cng the alert(ctr)
outside the while
triggers an infinite loop.
function foo2() {
var loop = true;
var abc = ["a","b","c"];
var ctr = 0;
while(loop) {
$("<img />").error(function () {
loop = false;
}).attr('src','images/letters/'+abc[1]+(ctr++)+".jpg");
}
alert(ctr);
}
Can anyone help clarify?
I would be mighty wary of doing what you are doing. You see, you are essentially spinning off an infinite loop, relying on an error
event thrown by JS to interrupt that loop. I imagine you are seeing the above behavior because calling alert()
is pumping messages, and giving a chance for the event to fire. In the latter example, you are just spinning the CPU, not giving anything else a chance to happen.
In your first snippet, the alert
function call inside the loop causes to stop it temporarily, presumably giving time to the error
callback to execute, setting the loop
flag to false
.
In your second snippet, when the alert
call is not present within the while
, the loop will execute many times, firing the browser's long-running script warning.
Javascript is single threaded and synchronic. If you remove the alert your loop will keep it busy and the error will not be thrown (it will be queued, actually) until the processing finishes. The alert makes your infinite loop pause for a while and lets Javascript process the queued events.
Can't see why, but seems like in the 2nd case there is a mixup of variable scope for some reason.
In most browsers, nothing will be written to the page until either the user is explicitly given control (in your case via an alert) or the javascript reaches it natural conclusion. the .error() is never made without the alert to pause the loop.
Would it be possible to write a for loop given the length of abc?
精彩评论