Karri
Karri

Reputation: 23

Shorter string causes the webpage to freeze

When the HTML Chart button is pressed it activates the createChart() method. However, if the value in the textarea is 25 characters or less, the webpages freezes. Also, only the letter "a" is being referenced with the method.

<script type = "text/javascript">
orangeBar = "./orange.gif";

function createChart()
    {

    alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
    textValue = document.getElementById("text").value;
    max = 0;

    for (i=0;i<alphabet.length;i++) 
    {
        value = numberOf(alphabet[i], textValue);
        if (value > max)
        {
            max = value;
        }
    }

    document.write(max);

}  

function numberOf(letter, string)
{
    count = 0;
    for (i=0; i<string.length; i++)
    {
        if (string[i].toLowerCase() == letter)
        {
            count++;
        }
    }
    return count;
}
</script>

Thank you. I'm brand new to coding. I can answer any questions.

Upvotes: 2

Views: 46

Answers (1)

Dmitry
Dmitry

Reputation: 7266

When you use for (i=0;i<alphabet.length;i++), i becomes a global variable. Then you use the same i in for (i=0; i<string.length; i++) and it changes you i of the createChart() function. Put var before i to make it local.

for (var i=0;i<alphabet.length;i++)

and

for (var i=0; i<string.length; i++)

Upvotes: 2

Related Questions