jquery setInterval or scroll

jquery, optimization, performance

Solution

Neither. I was just reading about JS/jQuery patterns. There is an example for the Window Scroll event: jQuery Window Scroll Pattern

var scrollTimeout;  // global for any pending scrollTimeout

$(window).scroll(function () {
    if (scrollTimeout) {
        // clear the timeout, if one is pending
        clearTimeout(scrollTimeout);
        scrollTimeout = null;
    }
    scrollTimeout = setTimeout(scrollHandler, 250);
});

scrollHandler = function () {
    // Check your page position
    if ($(window).scrollTop() > 200) {
        top.fadeIn();
    } else {
        top.fadeOut();
    }
    if (menuVisible) {
        quickHideMenu();
    }
};

Originally from here: Javascript Patterns

Problem

I am working on a project where i need to listen to the `scroll` event.. i wonder what is a better approach.. 1st Approach ``` function scroll() { if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); } } ``` 2nd Approach ``` function scroll() { didScroll = true; } setInterval(function() { if ( didScroll ) { didScroll = false; if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); } } }, 250); ``` Thanks :)

Original source