bkhosh2 bkhosh2 - 1 month ago 5x
Javascript Question

Underscore.js Debounce not Working Properly with Scroll

I am trying to use the

Underscore.js function to limit the number of AJAX POST requests that are sent.

My code is supposed to only execute the AJAX once the user has scrolled to the bottom of the page and I've tried using
to wait 2 seconds before sending another request. Once I scroll to the bottom, the AJAX is executed properly, however, if I keep scrolling after I've reached the bottom, another AJAX request is sent before the 2 seconds is up.

I've tried using
as well.

function ajaxFunction() {
type: "POST",
url: "SearchResults",
data: { skipAmount: $('.product-box').length, search: search },
success: function (response) {

if (response != null && response.success) {

error: function (XMLHttpRequest, textStatus, errorThrown) {
if (debug) {

function debounceAjaxFunction() { _.debounce(ajaxFunction(), 2000); }

$(window).scroll(function () {

if ($(window).scrollTop() + $(window).height() == $(document).height()) {




You are calling the function in your debounce argument

    _.debounce(ajaxFunction(), 2000);

when you should just be passing its reference as an argument

    _.debounce(ajaxFunction, 2000);

and then set a variable to call from your scroll function

   var debounceAjaxFunction = _.debounce(ajaxFunction, 2000);

The documentation is here for reference http://underscorejs.org/#debounce and the relevant part is

    var lazyLayout = _.debounce(calculateLayout, 300);