jquery setInterval或scroll

Luc*_*oni 8 optimization performance jquery

我正在开展一个项目,我需要听听这个scroll活动..我想知道什么是更好的方法..

第一种方法

 function scroll() {
    if ($(window).scrollTop() > 200) {
        top.fadeIn();
    } else {
        top.fadeOut();
    }
    if (menuVisible) {
      quickHideMenu();
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种方法

      function scroll() {
          didScroll = true;
      }

      setInterval(function() {
          if ( didScroll ) {
              didScroll = false;
              if ($(window).scrollTop() > 200) {
                  top.fadeIn();
              } else {
                  top.fadeOut();
              }
              if (menuVisible) {
                quickHideMenu();
              }
          }
      }, 250);
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

小智 19

都不是.我刚刚阅读有关JS/jQuery模式的内容.Window Scroll事件有一个例子: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();
    }
};
Run Code Online (Sandbox Code Playgroud)

最初来自这里:Javascript模式