How do I throttle in jQuery only on a certain condition, and execute immediately otherwise?
-
27-04-2021 - |
Question
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?
Solution
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.
OTHER TIPS
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?