Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript event handling scroll event with a delay

Can someone explaine and help me with this. My webpage is slugish because the scroll function is dragging it down. I need to add a delay but don't understand how to do this.

$(window).scroll(handleScroll);
like image 785
Daniel Haro Avatar asked Aug 17 '12 16:08

Daniel Haro


People also ask

How do I add a scroll delay?

You can add a delay function . delay() before the . animate() function, this will delay the animation by 3secs.

How do you trigger an event on scroll?

The scroll() method is used to trigger the scroll event or attach a function to run when scrolling occurs. The scroll event occurs when a scrollbar is used for an element. The event is triggered when the user moves the scrollbar up or down. We can use the CSS overflow property for creating a scrollbar.

Does scroll event bubble?

The scroll event does not bubble up. Although the event does not bubble, browsers fire a scroll event on both document and window when the user scrolls the entire page.


2 Answers

You could write a simple throttle debounce function to limit the times per second the scroll event will be handled.

function debounce(method, delay) {
    clearTimeout(method._tId);
    method._tId= setTimeout(function(){
        method();
    }, delay);
}

$(window).scroll(function() {
    debounce(handleScroll, 100);
});

This will make sure there's at least 100ms between each call to handleScroll (or, in other words, it's called at most 10 times per second).


As zzzzBov pointed out, what Zakas describes as a throttle function is actually a debounce function. The difference is that debounce discards the superfluous scroll events, while a throttle function should queue them up to be handled later (but at a given maximum rate).

In the case of scroll events, you don't want real throttling.

like image 125
Peter-Paul van Gemerden Avatar answered Sep 21 '22 17:09

Peter-Paul van Gemerden


For scroll you most likely need throttle function like in Lodash or Underscore, great example:

function throttle(func, timeFrame) {
  var lastTime = 0;
  return function () {
      var now = new Date();
      if (now - lastTime >= timeFrame) {
          func();
          lastTime = now;
      }
  };
}

This is simple implementation from this repo

like image 25
Oleksandr Pyrozhok Avatar answered Sep 19 '22 17:09

Oleksandr Pyrozhok