JS 节流

作为前端的小白,在做项目的过程中,一般只考虑到实现功能,并没有考虑到性能的问题。

比如说,下拉加载更多的这个功能和resize()是特别耗费性能的。此时就要想到节流了。

节流:就是然一个函数无法在短时间内连续的执行,只有上一函数执行后过了你所能规定的时间,才能继续执行以下的操作。

节流原理:原理其实很简单,用个定时器控制一下就好,但是,在用之前,注意,要清空定时器。自我认为,定时器这种东西跟浮动差不多,随时用随时清理。

例子:

function isBottom(){
  var timer = setInterval(function(){
    $(window).bind('scroll', function(){
    var loadType = $("#ifHeight").contents().find(".load-news").attr("load-type");
    if(loadType == "true"){
      return;
    }
    var scroll = $(window).scrollTop();
    if(scroll>= $(document).height()-$(window).height()-100){
      $("#ifHeight").contents().find(".load-news").attr("load-type","true");
      $("#ifHeight").contents().find(".load-news").show();
      var news = $("#ifHeight").contents().find("input[name=news]:checked").val();
      var curIndex = $("#ifHeight").contents().find("#curIndex").val();
      document.getElementById("ifHeight").contentWindow.creatLi(parseInt(curIndex),10,news,false);
      var doc = $(window.top.document);
      var h=$("#ifHeight").contents().height();
      var ifHeight = doc.find("#ifHeight").css({
      height:h
     });
  }
})
},50)
}

代码的功能仅仅是为了父页面获取子页面的高度,然后更改父页面的高度。

主要想体现出,节流的功能。

posted @ 2016-09-13 10:42  马习习  阅读(639)  评论(0编辑  收藏  举报