美文网首页
防抖节流

防抖节流

作者: 红酒煮咖啡 | 来源:发表于2020-10-26 11:17 被阅读0次

防抖:当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次;如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
节流:持续触发的事件,在固定一段时间内执行一次。
例子:
防抖

//默认参照屏幕是640px,font-size:100px
window.onresize = r;
function r(resizeNum){
    var winW = window.innerWidth;
    document.getElementsByTagName("html[0].style.fontSize=winW*0.15625+"px";
    if(winW>window.screen.width&&resizeNum<=10){
        setTimeout(function(){
             r(++resizeNum);
        }, 100);
    }else{
        document.getElementsByTagName("body")[0].style.opacity = 1;
    }
};
setTimeout(r(0), 100);
//用js计算font-size的大小,用rem布局

节流(一般有时间戳和定时器两种方法)

//时间戳
       var throttle = function(func, delay) {
          var prev = Date.now();
          return function() {                
            var context = this;                
            var args = arguments;                
            var now = Date.now();                
        if (now - prev >= delay) {
          func.apply(context, args);                    
          prev = Date.now();                
        }            
      }        
}        
function handle() {            
  console.log(Math.random());        
}        
window.addEventListener('scroll', throttle(handle, 1000));
//定时器
var throttle = function(func, delay) {
    var timer = null;            
    return function() {
        var context = this;
        var args = arguments;
        if (!timer) {
            timer = setTimeout(function() {
                func.apply(context, args);
                timer = null;
            }, delay);
        }
    }
}
function handle() {
    console.log(Math.random());
}
window.addEventListener('scroll', throttle(handle, 1000));

总结:
防抖是频繁触发时只执行最后一次事件处理函数;
节流是控制事件处理函数在一段时间内处理一次。

相关文章

网友评论

      本文标题:防抖节流

      本文链接:https://www.haomeiwen.com/subject/mvkamktx.html