Javascript/JQuery How to prevent function from repeatedly executed when holding down key?
Let suppose we have the following JQuery Code:
$(document).bind('keyup', function(e) {
arrows=((e.which)||(e.keyCode));
switch (arrows){
case 37:
executeMyfunction();
break;
}
});
If a user holds down the left arrow key (37) the executeMyfunction()
is repeatedly called.
How can I prevent this from happenin开发者_如何学运维g?
I thought keyup
would trigger only if key is released but its not working (that's why I use keyup
; keydown
does not work either).
I believe you have to unbind the event. I think it should not be keyup
, but keypress
or keydown
.
Probably something like this.
$(document).bind('keydown', function(e) {
arrows=((e.which)||(e.keyCode));
switch (arrows){
case 37:
executeMyfunction();
$(document).unbind('keydown');
break;
}
});
You will have to rebind the function on keyup
if you want to use the event again:
$(document).bind('keyup', function(e) {
switch (arrows){
case 37:
$(document).bind('keydown');
break;
}
})
Look at: http://api.jquery.com/unbind/
Well, you can always debounce the call to your function. That is, if you want your function to be called after the event has not been fired for a short period of time.
精彩评论