cor*_*zza 7 html javascript variables settimeout
我会很快,直接跳到案件中.代码被评论,所以你知道我的意图.基本上,我正在构建一个基于HTML5的小型游戏,并且反对在服务器或cookie中保存内容,我只是向玩家提供一个级别代码.当玩家将代码(以简单散列的形式)输入文本输入字段,并单击按钮以加载该级别时,将调用函数"l".该函数首先检索玩家的条目,然后遍历散列列表并进行比较.当匹配喜欢时,应该加载某个级别,但是存在错误.我做了一些调试,我发现迭代器("i")的值在setTimeout内发生了变化!我想暂停1秒,因为立即加载水平会太快,看起来很糟糕.
levelCodes = //Just a set of "hashes" that the player can enter to load a certain level. For now, only "code" matters.
[
{"code": "#tc454", "l": 0},
{"code": "#tc723", "l": 1},
]
var l = function() //This function is called when a button is pressed on the page
{
var toLoad = document.getElementById("lc").value; //This can be "#tc723", for example
for (i = 0; i < levelCodes.length; i++) //levelCodes.length == 2, so this should run 2 times, and in the last time i should be 1
if (levelCodes[i].code == toLoad) //If I put "#tc723" this will be true when i == 1, and this happens
{
console.log(i); //This says 1
setTimeout(function(){console.log(i)}, 1000); //This one says 2!
}
}
Run Code Online (Sandbox Code Playgroud)
其他人已经写出了你获得的行为的原因.现在解决方案:将setTimeout线路更改为:
(function(i) {
setTimeout(function(){console.log(i)}, 1000);
})(i);
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为它将变量的当前值捕获i到另一个闭包中,并且该闭包内的变量不会改变.