判断scroll时需要用到函数节流:
throttle:function(method,context){ //一个函数节流的函数 clearTimeout(method.tId); method.tId=setTimeout(function(){ method.call(context); },100); }, addEvent:function(){ //当鼠标滚到最下面时,依次加入一定数量的图片 var pubu=this; var method=function(){ var that=document; var buffer=that.documentElement.scrollHeight-that.documentElement.clientHeight; if(window.scrollY===buffer) { pubu.insertList(); } }; document.addEventListener("scroll",function(){ pubu.throttle(method); });return this; }
总结:
某些代码不可以在没有间断的情况连续重复执行
第一次调用函数,创建一个定时器,在指定的时间间隔之后运行代码
当第二次调用该函数时,它会清除前一次的定时器并设置另一个。目的是确保只有在执行函数的请求停止了一段时间之后执行。
var processor = {
var timeoutId=null;
performProcessor:function(){
}
process:function(){
var that=this;
alert(typeof that);
clearTimeOut(this.timeoutId);
this.timeoutId = setTimeOut(function(){
that.performProcessor();
},120);
alert(typeof that);
}
};
processor.process();
用一个函数进行简化,这个函数可以自动进行定时器的设置和清除
function throttle(method,context){
clearTimeout(method.tId);
method.tId = setTimeout(function(){
method.call(context);
},100
);
}