使用setTimeout的for循环将数字打印到控制台 [英] for loop with setTimeout prints number to console

查看:270
本文介绍了使用setTimeout的for循环将数字打印到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有关闭包的内容并找到了此代码。

I read about closures and find this code.

for(i=0;i<5;i++){
    setTimeout(function(){
        console.log(i);
    },2000)
}

2秒后输出5次5次。我了解这一点,但是在他出现之前有五个数字。当我再次执行此代码时,它进行了更改,将其旧值增加了5。它是什么?在控制台上编写代码,查看其输出,然后解释一下它是什么?

This outputs 5 number 5 times after 2 second. I understand this but before five appears there is number above him. And when I execute again this code it changes it adds 5 to his old value. What is it? Write code on console, see what it outputs then explain me what is it?

推荐答案

这是所评估值的结果值语句,对于循环来说,它是循环主体中最后一条语句的结果值,它是 setTimeout 调用的返回值。并且返回计时器ID(通过该ID取消超时)。

It's the "result" value of the evaluated statement, which for a loop is the result value of the last statement in the loop body, which is the return value of the setTimeout call. And that returns a timer id (which allows you to cancel the timeout).

您还可以通过更简单的语句看到此行为:

You also can see this behaviour with more simple statements:

> 0;
< 0
> console.log(1);
  1  // the output of the log()
< undefined
> var i=2;
< undefined // a declaration has no result
> var i=3; i;
< 3
> for (;i<3;i++) 4;
< undefined // the body was not evaluated
> for (;i<4;i++) 5;
< 5

注意前导箭头如何表示输入和结果输出。

Notice how the leading arrow represents input and result output.

这篇关于使用setTimeout的for循环将数字打印到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆