Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 8 years ago

keydown function refiring more and more times each time i press key (javascript)?

this fires once the first time I press a key, then fires more and more in subsequent presses, until after a few presses, it runs thousands of times, slowing the program down considerably (and messing up the points). Do you know what could be wrong with it?

I don't think it has anything to do with what's below the first line, since I've tested it, and it behaves the same way regardless of what I put there, as long as the syntax is fine.

$('#myCanvas').keydown(function(e){

if (curClef === "Treble") {

var n = e.which;

var noteCodeArray = [70,69,68,67,66,65,71,70,69,68,67,66,65,71,

70,69,68,67,66,65,71,70,69,68,67,66,65,71];

if (noteCodeArray[y]=== n) {

curPoints++;

status = "correct";

clickStopper(status);

}

else if (noteCodeArray[y]!== n) {

points--;

status = "incorrect";

clickStopper(status);

}

}

if (curClef === "Bass") {

var n = e.which;

var noteCodeArray = [65,71,70,69,68,67,66,65,71,

70,69,68,67,66,65,71,70,69,68,67,66,65,71,70,69,68,67,66];

if (noteCodeArray[y]=== n) {

points++;

status = "correct";

clickStopper(status);

}

else if (noteCodeArray[y]!== n) {

points--;

status = "incorrect";

clickStopper(status);

}

}

});

1 Answer

Relevance
  • 8 years ago
    Favorite Answer

    The last time I answered one of your questions, you deleted It afterwards, that was weird. Moving on to this question, I have two possibilities for what the problem might be. Firstly, where does the variable 'y' comes from, here:

    if (noteCodeArray[y]=== n) {

    nodeCodeArray[y], at this point, is 'undefined'. On the other hand, It is probably inside a loop, this is where I think the problem lies. The code starting from:

    $('#myCanvas').keydown(function(e){

    ...

    Is inside a loop and being called many times while you're looping through the elements in this array:

    var noteCodeArray = [70,69,68,67,66,65,71,70,69,68,67,66,65,…

    70,69,68,67,66,65,71,70,69,68,67,6…

    Every time you hit a key, the code starting here:

    $('#myCanvas').keydown(function(e){

    ...

    Is being called multiple times, the result is that your program will crash.

Still have questions? Get your answers by asking now.