zoukankan      html  css  js  c++  java
  • vue 防抖节流方案实例

    函数防抖(debounce):当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。举个栗子,持续触发scroll事件时,并不执行handle函数,当1000毫秒内没有触发scroll事件时,才会延时触发scroll事件。

    函数节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。节流通俗解释就比如我们水龙头放水,阀门一打开,水哗哗的往下流,秉着勤俭节约的优良传统美德,我们要把水龙头关小点,最好是如我们心意按照一定规律在某个时间间隔内一滴一滴的往下滴。举个栗子,持续触发scroll事件时,并不立即执行handle函数,每隔1000毫秒才会执行一次handle函数。

    防抖实例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <script>
    const delay = (function () {
     let timer = 0
     return function (callback, ms) {
      clearTimeout(timer)
      timer = setTimeout(callback, ms)
     }
    })()
    export default {
    methods:{
    fn() {
       delay(() => {
        //执行部分
       }, 500)
    }
    }
    }
    </script>

    节流实例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    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));
  • 相关阅读:
    C#中Windows通用的回车转Tab方法
    对Form_Load事件的一点想法
    关于粉笔灰对教师影响的解决方案
    今天才发现MSSQLServer2000的排序功能原来这样
    C# 2.0与泛型
    (收藏)Anders Hejlsberg谈C#、Java和C++中的泛型
    对接口interface的一点想法
    马的遍历
    推荐软件:工作时间提醒器
    pgpoolII 介绍
  • 原文地址:https://www.cnblogs.com/Taiweis/p/14380963.html
Copyright © 2011-2022 走看看