user6742604
user6742604

Reputation:

How to implement Ben Alman's debounce jQuery?

I'm using this project: https://github.com/cowboy/jquery-throttle-debounce

My code is -sorta- working, but the debounce is being ignored. So the waterfall function is called on every image load but the 2 second delay is not being respected. No errors are being shown.

What is the correct way to implement this? I've been fiddling with this for 3 hours now, but can't find a solution.

(function($) {
  $(document).ready(function(e) {

    var $waterfall = $('.waterfall');
    if ($waterfall.length) {
      $waterfall.waterfall({});
    }

    // sort the waterfall when images are loaded
    var $waterfall_images = $waterfall.find('img');
    $waterfall_images.each(function(j, image) {
      var $img = $(image);

      $img.load(function() {
        $.debounce(2000, $waterfall.waterfall('sort'));
      });

    });

  });
})(jQuery);
<ul class="waterfall">
  <li class="waterfall-item">
    <a href="hidden link" title="hidden title">
      <img alt="hidden alt" title="hidden title" data-srcset="hidden in this example" data-src="also hidden in this example" src="still hidden in this example" data-sizes="(min-width:440px) 300px, 95vw" class=" lazyloaded" sizes="(min-width:440px) 300px, 95vw"
      srcset="think I'll hide this one too">
      <span class="waterfallImgOverlay"></span>
    </a>

  </li>
</ul>

Upvotes: 2

Views: 148

Answers (1)

epascarello
epascarello

Reputation: 207501

You are calling the method, not assigning a reference. Easiest thing, wrap it in a function. Second thing is debounce returns a method, so you need to store what it returns and than call that method.

(function($) {
  $(document).ready(function(e) {

    var $waterfall = $('.waterfall');
    if ($waterfall.length) {
      $waterfall.waterfall({});
    }

    var waterfallSort = $.debounce(2000, function(){ $waterfall.waterfall('sort'); });

    // sort the waterfall when images are loaded
    var $waterfall_images = $waterfall.find('img');
    $waterfall_images.each(function(j, image) {
      var $img = $(image);

      $img.load( waterfallSort );

    });

  });
})(jQuery);

Upvotes: 1

Related Questions