DavidBoe
DavidBoe

Reputation: 17

How to fixe repeated callbacks in jQuery

I have a problem with my jQuery code, that happens when I scroll to bottom to load more content.

My code:

$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.9)
{
MyFonction();
}
});

When I scroll past the 90% mark of the page, I get repeated callbacks from MyFonction -- it is called multiple times.

Is there is a solution to make only one callback per scrolling?

Upvotes: 0

Views: 48

Answers (1)

cssyphus
cssyphus

Reputation: 40038

I think you are looking for the debounce and throttle functions - two similar (but different!) techniques to control how many times we allow a function to be executed.

The Debounce technique allow us to "group" multiple sequential calls in a single one.

The Throttle technique only allows our function to execute once every X milliseconds.

Here are some very good articles and examples:

How to change text element based on input text field in HTML using Javascript?

https://remysharp.com/2010/07/21/throttling-function-calls

https://css-tricks.com/debouncing-throttling-explained-examples/

https://davidwalsh.name/javascript-debounce-function


Another idea, that might be more suitable to this inquiry, is to also use a parent-scope variable to say whether you've scrolled past the 90% marker or not. Even using a throttler/debouncer, you will still get additional calls if the user stops and then starts again.

As a general rule, we usually use a debouncer whenever querying the .scroll() because there are so many events generated - but at 90%, you want to do something and not receive any further notifications until the next marker. So, use a variable for each marker and only check the scroll for that marker when that marker's variable is turned on.

Upvotes: 1

Related Questions