Skip to content Skip to sidebar Skip to footer

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:

Solution 1:

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){    
       case37:    
          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){    
      case37:
         $(document).bind('keydown');
         break;
    }    
})

Look at: http://api.jquery.com/unbind/

Solution 2:

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.

Post a Comment for "Javascript/jquery How To Prevent Function From Repeatedly Executed When Holding Down Key?"