Problem waiting til function has finished executing before it tries to execute again
-
03-07-2019 - |
Question
I'm using the $(window).scroll(); to specify a function to be call for when the user scrolls too close to the top or bottom.
The function takes a second to execute, and if they continue scrolling, it executes multiple times before the first one has even finished.
Is there any way I can let the function start executing and then tell the $(window).scroll() function that it needs to wait before executing that function again?
Solution
You could set a boolean that you're already checking scroll position:
checkingPosition = false;
$window.scroll(function() {
if(checkingPosition) return;
checkingPosition = true;
//do stuff
checkingPosition = false;
});
OTHER TIPS
I'd do something like this to avoid scope issues/confusion by encapsulating the data into an object... in this case, the jQuery object (on the window element):
$(function() {
$(window).data('checking_scroll',false);
$(window).scroll(function() {
if($(this).scrollTop() >= 200 /* or whatever... */) {
if($(this).data('checking_scroll') === true) {
return false;
} else {
whatever_function();
}
}
});
});
function whatever_function() {
$(window).data('checking_scroll',true);
// do all your stuff...
$(window).data('checking_scroll',false);
}
... but that's just me.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow