Scroll event firing too many times. I only want it to fire a maximum of, say, once per second

后端 未结 8 721
再見小時候
再見小時候 2020-11-27 12:24

I have a page with \"infinite scroll\". It calculates the difference between the end of the page and the current page and loads more content if this difference is small enou

8条回答
  •  自闭症患者
    2020-11-27 12:46

    var now = new Date().getTime();
    $(window).scroll( function () {
        if (window.pageYOffset > loadMoreButton.offsetTop - 1000)
        {
            if (new Date().getTime() - now > 1000)
            {
                console.log("Task executed once per second");
                now = new Date().getTime();
            }
        }
    });
    

    Or

    You can use Throttling fonction calls: throttling-function-calls

    function throttle(fn, threshhold, scope) {
      threshhold || (threshhold = 250);
      var last,
          deferTimer;
      return function () {
        var context = scope || this;
    
        var now = +new Date,
            args = arguments;
        if (last && now < last + threshhold) {
          // hold on to it
          clearTimeout(deferTimer);
          deferTimer = setTimeout(function () {
            last = now;
            fn.apply(context, args);
          }, threshhold);
        } else {
          last = now;
          fn.apply(context, args);
        }
      };
    }
    

    You can call it like this:

    $('body').on('mousemove', throttle(function (event) {
      console.log('tick');
    }, 1000));
    

提交回复
热议问题