Debouncer on Delegated Event

How to set a debouncer on a delegated event

by 4lackof

HTML

<div>
  <div id="foo-one">Foo1</div>
  <div id="bar-one">Bar1</div>
  <div id="counter-one"><span>Counter1</span></div>
</div>
<div>
  <div id="foo-two">Foo2</div>
  <div id="bar-two">Bar2</div>
  <div id="counter-two"><span>Counter2</span></div>
</div>
<div>
  <div id="foo-three">Foo3</div>
  <div id="bar-three">Bar3</div>
  <div id="counter-three"><span>Counter3</span></div>
</div>

CSS

div > div {
  height: 64px;
  width: 64px;
  border: 1px solid black;
  display: inline-block;
}

#counter-one,
#counter-two,
#counter-three {
  background-color: red;
}

JavaScript

//debounce function by davidwalsh: https://davidwalsh.name/javascript-debounce-function
//Returns a function, that, as long as it continues to be invoked, will not
//be triggered. The function will be called after it stops being called for
//N milliseconds. If `immediate` is passed, trigger the function on the
//leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this,
      args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};
$(document).on('click', '#foo-one, #bar-one', debounce(function(e) {
  $('#counter-one').append('<span>1</span>');
}, 350));
$('#foo-two').click(debounce(function(e) {
  $('#counter-two').append('<span>2</span>');
}, 350));
$('#bar-two').click(debounce(function(e) {
  $('#counter-two').append('<span>2</span>');
}, 350));
$(document).on('click', '#foo-three, #bar-three', function(e) {
  var $this = $(this);
  if ($this.is('#foo-three')) {
    //should happen immediately
    $('#counter-three').append('<span>3</span>');
  }
  if ($this.is('#bar-three')) {
    //should debounce
    debounce(function() {
    	$('#counter-three').append('<span>3</span>');
    }, 350);
  }
});