2017-03-06 181 views
1

我正在使用Prestashop网站的插件,每次点击按钮时都会调用Instagram API。我需要这样的事情发生在滚动,所以:点击滚动按钮,每隔几秒钟点击一次

$(window).scroll(function() { 
     if($(window).scrollTop() + $(window).height() > $(document).height() - 200) { 
     $("#pwip__loadmore").click(); 
     } 
}); 

这种运作良好,但是,点击按钮的方式太多次,并导致被重复一样的图像错误。每次点击后如何设置休息或暂停时间?像点击一样,等待2秒钟,然后才能进行下一次点击?

+0

怎么样'setTimeout'? –

+0

我尝试了几种方法无济于事,你会怎么做? – Sergi

回答

3

这个怎么样

var clickable = true; 

$(window).scroll(function() { 
    if($(window).scrollTop() + $(window).height() > $(document).height() - 200) { 
     if(clickable){ 
      $("#pwip__loadmore").click(); 
      clickable = false; 
     } 
     setTimeout(function(){ 
      clickable = true; 
     }, 2000); 
    } 
}); 
+0

这很完美。谢谢。 – Sergi

0

这是因为onscroll事件会在时间的短短多次调用。您可以使用类似debouncing

反弹功能不允许在给定时间范围内多次使用回调。将回调函数分配给频繁触发事件时,这一点尤为重要。

// 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. 
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); 
    }; 
}; 

你会通过防抖动功能来执行功能,以毫秒为单位的消防速率限制。下面是修改后的代码,以满足您的要求:

var myEfficientFn = debounce(function() { 
    if($(window).scrollTop() + $(window).height() > $(document).height() - 200) { 
    $("#pwip__loadmore").click(); 
    } 
}, 1000); 

window.addEventListener('scroll', myEfficientFn); 

参考

DavidWalsh