zoukankan      html  css  js  c++  java
  • 防抖与节流原理与区别

    一:函数的节流: 一定时间内只触发一次 
    
    可以是直接给一个定时器,按时触发,
    
    // 函数节流 var canRun = true; document.getElementById("throttle").
    
    onscroll = function(){
    
    if(!canRun){ // 判断是否已空闲,如果在执行中,则直接return return;
    
    }
    
    canRun = false;
    
    setTimeout(function(){
    
    console.log("函数节流"); canRun = true; 
    }, 300); };
    
    也可以根据一个条件判断触发
    节流demon   http://demo.deanhan.cn/suggestion.html
      二:函数防抖 在规定的时间内只触发一次,如果多次触发,清除上次触发的事件,重新计算时间, 
    // 防抖就是事件 :多次触发事件后,
    //事件处理函数只执行一次,
    //并且是在触发操作结束时执行
    //事件多次触发清除之前的定时器
    let timer;
    window.onscroll = function() {
    console.log(12)
    if (timer) {
    clearTimeout(timer)
    }
    timer = setTimeout(function() {
    //滚动条位置
    let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    console.log('滚动条位置:' + scrollTop);
    timer = undefined;
    }, 200)
    }
    
     
    
    
  • 相关阅读:
    撕裂寂寞
    创业中的“孙子兵法”
    生命的颜色占卜
    常常激励我们的36句话
    创建自己的3D虚拟身体!
    富人和穷人的八大差异
    有时,孤单是一种享受
    JavaScript类
    上网的十条基本礼节
    程序设计中的感悟
  • 原文地址:https://www.cnblogs.com/tiangeng/p/10097943.html
Copyright © 2011-2022 走看看