0

Is it possible to debounce the click of a link? If a user clicks too many times too fast on a pjax link it'll break the load of new content.

$(document).on('click', 'a[data-pjax]', loadNewContent);

var $target = $('main.content section.context'),
$fake = $('main.fake'),
$fakeContext = $('main.fake section.context');

function loadNewContent() {

    event.preventDefault();

    var $this = $(this),
    url = $this.attr('href');

    $fake.addClass('is--loading');

    $.pjax({
        url: url,
        fragment: 'body',
        container: $fakeContext
    });

    $fake.one(transitionEnd, function() {
        $target.html($fake.find('section.context').html());
        $fake.removeClass('is--loading');
        $fake.off(transitionEnd);
    });

}

Any thoughts? I tried this, but it stopped the loadNewContent from firing. (https://github.com/cowboy/jquery-throttle-debounce)

$(document).on('click', 'a[data-pjax]', $.debounce(1000, true, function() {
    loadNewContent();
}));
John the Painter
  • 2,495
  • 8
  • 59
  • 101

1 Answers1

2

Something like this would work :

var callWaiting = false;
callAjax() {
  if(!callWaiting) {
    callWaiting = true;
    makeHttpCall(url, data, function(response) {callWaiting = false;});
    callWaiting = false;
  }
}
binariedMe
  • 4,309
  • 1
  • 18
  • 34