views:

188

answers:

1

So I have the following code, which should append 'true' to the div "test" every 25ms as long as key 68 (the d key) is being pressed, right?

<html>
<body>
<div id="test"></div>
<script type="text/javascript">
var key=false;
var keyDown=function(e) {
 if (e.keyCode==68) {
  key=true;
 }
}
var keyUp=function(e) {
 if (e.keyCode==68) {
  key=false;
 }
}
document.onkeydown=keyDown;
document.onkeyup=keyUp;
var run=function() {
 document.getElementById('test').appendChild(document.createTextNode(key+'\n'));
 t = setTimeout('run()', 25);
}
var t = setTimeout('run()', 25);
</script>
</body>
</html>

Save the code, load it in a browser and hold down on the d key. If I'm not crazy, you'll see that it occasionally appends 'false' even though the d key was never released. (I've tried this in FF and Chrome in Linux and Vista). Anybody happen to know why, or have a workaround?

Edit: It seems to behave as expected in FF running in OS X.

A: 

I just tried it in IE7. After changing "e.keyCode" to "event.keyCode", it worked just as you expected.

Have you actually tried the code you pasted here, or are you working with other code that may have a bug in it?

Edit

I just ran this in Chrome. Again, it behaves as expected.

Are you using a wireless keyboard that could be susceptible to interference or battery weakness that wouldn't affect normal keyboard use, but becomes visible in this test?

John Fisher
I was working on a larger chunk of code, but managed to isolate the problem, which is the code you see above.Since I wasn't working with IE, I neglected to add the logic to use event instead of e if the browser is IE.
vonkow
I've tried a number of keyboards, PS/2 and USB. Just tried it again and it seems to show false a little more often in FF than Chrome (in Ubuntu), but still the occasional false in Chrome. How many seconds did you let it run in Chrome?
vonkow
I ran it in Chrome on Vista for at least 10 seconds.
John Fisher
Yea, it seems to be working in Chrome in Vista for me as well. Maybe this is an Ubuntu problem?
vonkow
Since you've tried several keyboards and don't have the problem in the same brower in Vista, I would feel safe pointing the finger at Ubuntu.
John Fisher