Seems like it's only my word)
Is there a way to execute a function after some time ?
I'm trying to write an advanced scrollspy script for my site and what i was thinking about is to execute onScroll action not immediately but after some time. If user scrolls fast and with many stops, i want scrollspy to refresh navigation links only at stop, and if user scrolls slowly (and maybe without stops) i want scrollspy to refresh nav links every 0.6s for example.
Unfortunately, i dunno where to begin.
I'm trying to upgrade this code:
var lastId,
topMenu = jQuery(".a1-nav"),
topMenuHeight = document.querySelector('header .top-header').offsetHeight;
menuItems = topMenu.find("a"),
scrollItems = menuItems.map(function(){
var item = jQuery(jQuery(this).attr("href"));
if (item.length) { return item; }
});
menuItems.click(function(e){
var href = jQuery(this).attr("href"),
offsetTop = href === "#" ? 0 : jQuery(href).offset().top-topMenuHeight+1;
jQuery('html, body').stop().animate({
scrollTop: offsetTop
}, 300);
e.preventDefault();
});
jQuery(window).scroll(function(){
var fromTop = jQuery(this).scrollTop()+topMenuHeight;
var cur = scrollItems.map(function(){
if (jQuery(this).offset().top < fromTop)
return this;
});
cur = cur[cur.length-1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
console.log(id);
menuItems
.removeClass("active")
.filter("[href=#"+id+"]").addClass("active");
}
});
Well, the way I would do it is something like:
var debounce;
var interval;
$(window).on('scroll', function() {
if (typeof debounce != "undefined") {
clearTimeout(debounce);
} else if (typeof interval == "undefined" {
interval = setInterval(update, 500);
}
debounce = setTimeout(function() {
interval = clearInterval(interval);
}, 1000);
});
var update = function() {
//your scroll code here
}
This makes it so when they've started scrolling, we run "update" every half second, and once they've stopped scrolling for one second, we clear the interval. No need to run it again since we know it ran at least once since they stopped scrolling.
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