节流和防抖

来源:互联网 发布:python 招聘 编辑:程序博客网 时间:2024/04/30 14:45

事件连续触发,导致页面卡顿。

  • 窗口缩放和页面滚动
  • mousemove、keydown、mousedown、keyup

节流

隔一段时间,执行一次。就像水龙头滴水一样。

var throttle = function(){  var last = 0;  return function(){    var curr = new Date();    if (curr - last > 1000){//滚动时,1s钟执行1次      console.log(1);      last = curr;     }  }}window.onscroll=throttle();

防抖

延迟一段时间再执行,如果在延迟的时间内继续触发,会重新计算。

function debounce(){    var timer;    return function(){        if(timer)clearTimeout(timer);        timer=setTimeout(function(){            console.log(1);        }, 1000);    }}window.onscroll=debounce();
1 0