Search code examples
javascripthtmlvariablessettimeout

setTimeout appears to be changing my variables! Why?


I'll be quick and jump straight to the case. The code is commented so you know my intentions. Basically, I'm building a small, HTML5 based game, and opposed to saving stuff on the server or in a cookie, I'll just provide the player a level code. When a player enters the code (in a form of a simple hash) into a text input field, and clicks a button to load that level, the function "l" is called. That function first retrieves the player's entries, then iterates through the list of hashes and compares them. When a match is fond, that certain level is supposed to be loaded, but there were errors. I did a little bit of debugging, and I found out that the value of the iterator ("i"), has changed inside a setTimeout! I want to pause 1 second, because loading the level immediately would be simply too quick and would look bad.

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!
        }
}

Solution

  • The for loop continuously increments i until the loop condition is met, even though the code in the for loop does not execute, when the code in the setTimeout executes it shows the current value of i - which is 2.