Here is a solution that does not require the use of an additional JS library or plugin, the purpose of which is simplicity. It may not be as effective as other implementations, but it is definitely a step forward from triggering the main event every time you scroll.
This was taken from this blog post by Danny Van Couthen. What I used to delay my onscroll() events for my back-to-top button on my blog.
var timer; $(window).scroll(function() { if(timer) { window.clearTimeout(timer); } timer = window.setTimeout(function() {
You can also improve performance by displacing variables from the callback function to avoid unnecessary recounts, for example, the value of $(window).height() or the height of some static div element that does not change after the page loads.
Here is an example that is adapted from my use case.
var scrollHeight = $("#main-element").height(); //never changes, no need to recalculate. $(window).on('scroll', function() { if (timer) window.clearTimeout(timer); timer = window.setTimeout(function() { var scrollPosition = $(window).height() + $(window).scrollTop(); if ($(window).scrollTop() < 500) $(".toggle").fadeIn(800); else $(".toggle").fadeOut(800); }, 150); //only fire every 150 ms. });
This limits the actual function to only be executed every 150 ms, otherwise the reset timer returns to 0 if 150 ms has not passed. Adjust the value according to what you need.
matrixanomaly Jun 24 '15 at 6:08 2015-06-24 06:08
source share