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);
You can add a delay function . delay() before the . animate() function, this will delay the animation by 3secs.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With