views:

172

answers:

2

Hi,

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?

+3  A: 

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;
});
seanmonstar
You would need to add a checkingPosition = false; after //do stuff
Paolo Bergantino
don't forget changing it back to false when the function is done executing
Nadia Alramli
+1  A: 

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.

KyleFarris