jQuery multiple clicks, wait until user stops clicking

Viewed 2571

I have a plus button to increase the number in a text field. When the text field value changes a #updateCartButton is triggered which updates the form through some other ajax/php code.

The problem I'm having is clicking 5 times on the plus button in rapid session also triggers #updateCartButton 5 times. I want #updateCartButton to be triggered once the user stops clicking the plus button, maybe after 500ms or something.

I tried to solve it setTimeout, like this, but it doesn't solve the problem:

  setTimeout(function () {
    $('#updateCartButton').trigger('click'); // trigger update button
  }, 500);

Is there a simple solution to this?

$(function() {
  $('.plus').on('click', function() {
    var oldVal = $('input').val();
    var newVal = (parseInt($('input').val(),10) + 1);
    
    $('input').val(newVal);
    $('#updateCartButton').trigger('click'); // trigger update button
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" class="plus">+</button>
<input type="text" value="1">

2 Answers
Related