Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching handlers to window scroll event [closed]

John Resig suggests using setInterval() in order to reduce the number of times the handler is called - see http://ejohn.org/blog/learning-from-twitter/

John's solution from the blog post:

var outerPane = $details.find(".details-pane-outer"),
    didScroll = false;
 
$(window).scroll(function() {
    didScroll = true;
});
 
setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        // Check your page position and then
        // Load in more results
    }
}, 250);

Can invoking a continues interval really be a sensible idea?

Would Michael Jackson's approach makes more sense as it doesn't mean we're constantly polling?

Michael's solution from the comments:

var timer = 0;

$(window).scroll(function () {
  if (timer) {
    clearTimeout(timer);
  }

  // Use a buffer so we don't call myCallback too often.
  timer = setTimeout(myCallback, 100);
});

Can anybody share any advice / opinion?

like image 426
riscarrott Avatar asked Feb 08 '11 02:02

riscarrott


1 Answers

I was reading the same post, but ended with some mixed aproach.

Neither Jhon Resig nor MJ were fine to me. although I really apreciate the light they put on my research

Here is my code, which is executed as soon as the event is fired, but run only once every 250ms, when it is "re-enabled"

var scrollEnabled = true;

$(window).on('scroll', function(event) {
  if (!scrollEnabled) {
    return;
  }
  scrollEnabled = false; 
  console.log('i am scrolling');
  return setTimeout((function() {
    scrollEnabled = true;
    console.log('scroll enabled now');
  }), 250);
});
like image 175
Diego Dorado Avatar answered Sep 30 '22 13:09

Diego Dorado