简体   繁体   中英

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 moving 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?

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 .

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.

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.

看不出原因,但似乎在第二种情况下由于某种原因存在可变范围的混淆。

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?

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