0

My code is as follows.

script.js

var main = function(){
    for(var j=0; j<10; j++){
        for(var i=0; i<10; i++){
            setTimeout(function(){$('div').append(i*j);}, 1000*j);
        };
    };
};
$(document).ready(main);

index.html

<html>
    <head>
    </head>
    <body>
    <div></div>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="script.js"></script>
    </body>
</html>

I want to display

(sec1)00000000000

(sec2)00000000000123456789

(sec3)000000000001234567890246891012141618

......

, but it display

(sec1)100100100100100100100100100100

(sec2)100100100100100100100100100100100100100100100100100100100100

(sec3)100100100100100100100100100100100100100100100100100100100100100100100100100100100100100100

......

Why?What should I do?

1 Answers1

0

The for loops run to completion scheduling 100 setTimeout() calls. At that point, both i and j are pointing at the ending value for the for loops which is what they will be at when the setTimeout() callback gets called..

If you want to use i and j in the setTimeout() callback, you will have to create a closure to caputure their value uniquely for each cycle through the for loop.

There are many other answers that illustrate the details of how to do this. Here are a few:

Asynchronous Process inside a javascript for loop

Why is the loop assigning a reference of the last index element to?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979