setTimeout与JavaScript中的循环 [英] setTimeout with Loop in JavaScript

查看:64
本文介绍了setTimeout与JavaScript中的循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常琐碎的问题.对于带有setTimeout的简单循环,像这样:

I have a very trivial question. For a simple loop with setTimeout, like this:

for (var count = 0; count < 3; count++) {
    setTimeout(function() {
        alert("Count = " + count);
    }, 1000 * count);
}

控制台给出这样的输出:

console gives an output like this:

Count = 3
Count = 3
Count = 3

不确定为什么这样的输出.有人可以解释吗?

Not sure why the output like this. Anyone could explain, please?

推荐答案

这与如何在JavaScript中处理作用域和提升有关.

This has to do with how scoping and hoisting is being treated in JavaScript.

您的代码中发生的事情是JS引擎将您的代码修改为此:

What happens in your code is that the JS engine modifies your code to this:

var count;

for (count = 0; count < 3; count++) {
    setTimeout(function() {
        alert("Count = " + count);
    }, 1000 * count);
}

当运行 setTimeout()时,它将首先在 count 之后查找它自己的作用域,但找不到它,因此它将开始查找关闭的功能(称为关闭) setTimeout 函数,直到找到 var count 语句为止,该语句的值为3,因为循环将在执行第一个超时函数之前完成.

And when setTimeout() is being run it will first look in it's own scope after count but it won't find it so then it'll start looking in the functions that closes (this is called closures) over the setTimeout function until it finds the var count statement, which will have the value 3 since loop will have finished before the first timeout function has been executed.

更多代码-巧妙地解释了您的代码实际上是这样的:

More code-ily explained your code actually looks like this:

//first iteration
var count = 0; //this is 1 because of count++ in your for loop.

for (count = 0; count < 3; count++) { 
    setTimeout(function() {
        alert("Count = " + 1);
    }, 1000 * 1);
}
count = count + 1; //count = 1

//second iteration
var count = 1;

for (count = 0; count < 3; count++) {
    setTimeout(function() {
        alert("Count = " + 2);
    }, 1000 * 2);
}
count = count + 1; //count = 2

//third iteration
var count = 2;

for (count = 0; count < 3; count++) {
    setTimeout(function() {
        alert("Count = " + 3);
    }, 1000 * 3);
}
count = count + 1; //count = 3

//after 1000 ms
window.setTimeout(alert(count));
//after 2000 ms
window.setTimeout(alert(count));
//after 3000 ms
window.setTimeout(alert(count));

这篇关于setTimeout与JavaScript中的循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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