Skip to content
Advertisement

If buttons of item were inactive for 2 sec – make action

I would like to implement such logic:

  • User clicks on “Plus” or “Minus” button.
  • If the user don’t click at any of those buttons for 2 seconds, then we assume that current quantity should be sent to the server.

Right now, I have three buttons: “Plus” – increments quantity by 1 and changes the value at page. “Minus” – decreases quantity by 1 and changes the value at page. “Confirm” – The button that sends request with current quantity parameter to Spring Boot controller and changes quantity on server side. I would prefer to avoid this button, because it adds complexity.

Is there a convenient way to get rid of the confirm button? The only way I know how we can do this is by sending request to controller on each “Plus” or “Minus” button click. But it seems that this approach will be inefficient.

JavaScript
JavaScript

Fiddle

PC: It seems that my question is related to this topic(https://stackoverflow.com/a/7762539/14308420). But I’m not sure if I should apply it in my case and how to do it.

I extracted the logic of submit button to function updateQuantityOnServer(button). And after adding this line:

JavaScript

I got a warning:

Argument type void is not assignable to parameter type TimerHandler Type void is not assignable to type string | Function Type void is not assignable to type Function.

As I understand, it’s caused because I send button as parameter. But I use this button to get parameters…

Advertisement

Answer

Look at the changeQuantityAjax function for the implementation of clearTimeout and setTimeout together, making a “minimal” delay of 2 seconds after the last user action.

From each button click, this was passed to the getIdandQuantity function.

It does not change much things in the logic, but notice the .parents() instead of parent().parent().parent().

JavaScript
JavaScript

Additionnally! You could easilly merge the 4 functions above (2 click handlers, getIdandQuantity and changeQuantityAjax) into one single click handler.

JavaScript
JavaScript
Advertisement