To ignore key events caused by key repeats, keep track of which keys were pressed during keydown and keyup .
var pressedKeys = []; function keydownHandler(e) { var isRepeating = !!pressedKeys[e.keyCode]; pressedKeys[e.keyCode] = true; switch (e.keyCode) { case !isRepeating && 39:
To stop the div from moving, you can track the interval identifiers in the array and clear the interval during the keyup event with something like clearInterval(intervalIds[e.keyCode]) , but I would probably switch to using setTimeout() and checking are closed whether they are the key. This way you do not need to track another variable.
var pressedKeys = []; function keydownHandler(e) { var isRepeating = !!pressedKeys[e.keyCode]; pressedKeys[e.keyCode] = true; switch (e.keyCode) { case !isRepeating && 39: movFwr(); break; } } function keyupHandler(e) { pressedkeys[e.keyCode] = false; } function movFwr() { if (pressedKeys[39] && currPos < 1000) { currPos += 10; a.style.left = currPos + "px"; setTimeout(movFwr, 50); } }
This way, you will also automatically stop repeating the function as soon as the div reaches the right edge, instead of waiting for the user to release the arrow key.
source share