优化根据 scrollTop 激活容器的函数

Optimization of function which activates container depending of scrollTop

我正在创建一个网站,其中有许多容器,当人们向下滚动时它们会被激活,而如果人们进一步滚动则会被停用。我担心这样滚动会变得非常参差不齐。也许你知道我该如何改进它?

$(window).scrollEnd(function(){ 
if( 200 < $(this).scrollTop() ) {
        if (1500 > $(this).scrollTop()) { 
                  if(fired == 0){
                    $("#loader_small").css("display", "block");
                    $('.section_two_video').load('test.html');
                    fired = 1;
                  }
            $(".section_two_video").stop().fadeIn("slow");
        }else {
            $(".section_two_video").stop().fadeOut("slow");
        }   
    } 
    else {
        $(".section_two_video").stop().fadeOut("slow");
    };
}, 300)

$.fn.scrollEnd = function(callback, timeout) {          
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

你可以下划线的去抖功能:

function _debounce(func, wait, immediate) {
    var timeout;

    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

来自文档:

Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If immediate is passed, trigger the function on the leading edge, instead of the trailing.

使用:

var func = _.debounce(function(e) {    
    // do work
}, 500); // once per 500ms

// Add the event listener
$(window).scrollEnd(func);