开发者

jquery delay changes queued function closure?

开发者 https://www.devze.com 2023-02-14 18:56 出处:网络
I have a very simple test page that tests jquery (1.4.2) queue and delay. for (var i = 1; i <= 5; i++) {

I have a very simple test page that tests jquery (1.4.2) queue and delay.

    for (var i = 1; i <= 5; i++) {
        $('#test')
        //.delay(50)
        .queue(function(next) {
            console.log(i);
            next();
        });
    }

Now when I run this code in FF with firebug, I get what I expected, 1 ~ 5.

However开发者_开发知识库, if I un-comment delay, I got 6 five times instead?

Can someone please help me clarify this?


The i is a single variable stored one time and shared by all iterations of the loop. Without the .delay() you're using the value of i right then, so it's what you expect. With the .delay() however, you're using what the value is later...and later it's what it ended up as at the end of the loop, 6.


@Nick provides an excellent explanation for why it behaves like this.

For completeness, you can "fix" this by capturing the current value of i in a new scope. JavaScript has only function scope, so you have to use a function to capture the value. E.g. you can use an immediate function:

for (var i = 1; i <= 5; i++) {
    $('#test')
    .delay(50)
    .queue((function(index) {
        return function(next) {
            console.log(index);
            next();
        }
    }(i))); // <- function gets called directly with `i` and the returned
            //    function is passed to queue.
}

DEMO


Well for the following code in firebug console on stackoverflow

for (var i = 1; i <= 5; i++) {
    $('#custom-header')
        //.delay(50)
        .queue(function(next) {
        console.log(i);
        next();
        });
}

On console, you get result

1
2
3
4
5
[div#custom-header]

And for code

for (var i = 1; i <= 5; i++) {
    $('#custom-header')
        .delay(50)
        .queue(function(next) {
        console.log(i);
        next();
        });
}

You get result

[div#custom-header]
6
6
6
6
6

[Explanation]:

From this we can conclude that dealay(50) delays the the evaluation of the function inside queue so [div#custom-header] is printed first and i is printed which is all 6 (by the moment) because the loop (which is not delayed) is evaluated first (only the printing function inside queue is delayed).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号