fangsterr
fangsterr

Reputation: 3820

How do I throttle in jQuery only on a certain condition, and execute immediately otherwise?

I'm using this jQuery plug-in for throttle support.

I have a text input variable called textbox set as follows, which will execute someFunction at most once every second:

textbox.keypress($.throttle(1000, someFunction(e)));

However, I want someFunction to execute immediately if the key pressed is the enter key. I'm not quite sure how to do this. Any suggestions?

Upvotes: 2

Views: 118

Answers (2)

osahyoun
osahyoun

Reputation: 5231

textbox.keypress(function(event) {
  if(event.which == 13){
    // Enter key has been preseed. Do something.
  } else {
    $.throttle(1000, function(){
      someFunction(event);
    })
  }
});

Keep in mind what you're passing for callbacks. Both 'someFunction' and '$.throttle' are being invoked directly, with their return values being passed as callbacks. To avoid this, wrap the functions in a function (lambda) as I have done above.

Upvotes: 2

Barry Chapman
Barry Chapman

Reputation: 6780

You will need to have in your code a handler for the 'ENTER' keypress and abort the $.throttle if that is the case. Can you paste more of your code maybe to give us a better idea of what to work with?

Upvotes: 0

Related Questions