zoukankan      html  css  js  c++  java
  • js防抖和节流

    防抖

    触发高频事件后,n秒内函数只执行一次,如果n秒内高频事件再次被触发则重新计算时间。
    

    思路:

    每次触发事件时,都取消之前的延时调用方法。
    
    function debounce(fn,wait) {
          let timeout = null; // 创建一个标记用来存放定时器的返回值
          let timeWait = wait || 1000
          return function () {
               const that = this,
                        args = arguments;
               clearTimeout(timeout); // 每当用户输入的时候把前一个 setTimeout clear 掉
               timeout = setTimeout(() => { 
                  fn.apply(that , args);//1,this 指向2,event 对象
               }, timeWait);
          };
     }
    
    

    防抖

    高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率
    

    思路:

    每次触发事件时都判断当前是否有等待执行的延时函数
    
    function throttle(fn,wait) {
          let canRun = true; // 通过闭包保存一个标记
          let timeWait = wait || 1000;
          return function () {
          		const that = this,
                         args = arguments;
    	        if (!canRun) return; // 在函数开头判断标记是否为true,不为true则return
    	        canRun = false; // 立即设置为false
    	        setTimeout(() => { // 将外部传入的函数的执行放在setTimeout中
    		          fn.apply(that,  args );
    		          // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。当定时器没有执行的时候标记永远是false,在开头被return掉
    		          canRun = true;
    	        }, 500);
          };
    }
    

    链接:
    JavaScript专题之跟着underscore学防抖
    JavaScript专题之跟着 underscore 学节流

  • 相关阅读:
    最大流之dinic
    HDU 2485
    最小费用最大流
    HDU 1533
    HDU 1402
    HDU 1498
    HDU 1281
    Codeforces 283E Cow Tennis Tournament 线段树 (看题解)
    Codeforces 983E NN country 思维 (看题解)
    Codeforces 494D Birthday 树形dp (看题解)
  • 原文地址:https://www.cnblogs.com/yihan123/p/13449290.html
Copyright © 2011-2022 走看看