关于javascript:在node.js的setTimeout中计数器没有增加?

counter is not incremented in setTimeout in node.js?

本问题已经有最佳答案,请猛点这里访问。

在下面的Node.js循环程序中,该循环执行了很多次,但为什么控件没有从循环中出来。我没有忘记这样做,我在setTimeout中增加了i的值。

1
2
3
4
5
6
7
8
9
10
function abc () {
  for(var i=0;i<5;) {
    console.log("executes loop");
    setTimeout(function(){
      console.log(i++);
    },0)
  }
}

abc();

您忘记了将i++放入循环中。

尝试一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<body>
 


\t
\t\twindow.onload = function function_name(argument) {
\t\t\t// body...

\t\tfunction abc () {
\t\t\tfor(var i=0;i<5;i++) {
\t\t\t\tconsole.log("executes loop");
\t\t\t\tsetTimeout(function(){
\t\t\t\t\tconsole.log(i++);
\t\t\t\t},0)
\t\t\t}
\t\t}

\t\tabc();
\t\t}

\t
</body>
</html>

由于超时,它退出了循环,因此当它返回时,i的值为5,因此它将在5之后打印。

已编辑

如果要在timeout

内部增加值

试试这个

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
<body>
 


\t
\t\twindow.onload = function function_name(argument) {
\t\t\t// body...

\t\tvar j = 0;

\t\tfunction abc () {
\t\t\tfor(var i=0;i<5;i++) {
\t\t\t\tconsole.log("executes loop");
\t\t\t\tsetTimeout(function(){
\t\t\t\t\ti++;
\t\t\t\t\tj = i-6;
\t\t\t\t\tconsole.log(j);
\t\t\t\t},0)
\t\t\t}
\t\t}

\t\tabc();
\t\t}

\t
</body>
</html>