js节流实现

场景: 在无限加载页面时,每隔一段时间去请求ajax, 而不是用户停下滚动时才去加载页面

时间戳实现

function throttle(func, delay){

    let prev = new Date();

    return funtion(){

       let contxt = this;

       let args = arguments;

       let now = new Date();

       if(new-prev >= delay){  // 时间间隔大于delay就会触发

           func().apply(contxt, args);

           prev = new Date();

       }

   }

}

 定时器实现

fucntion throttle(func,delay){

      var timer = null;

      return funtion(){

            var context = this;

            var args = arguments;

 if(!timer){

           timer = setTimeout(function(){

                func.apply(context,args);

                timer = null;

             },delay);

               }

        }

}

猜你喜欢

转载自blog.csdn.net/rongmingye/article/details/82459013