zoukankan      html  css  js  c++  java
  • 节流和防抖简单介绍

    前言

    因为在开发过程中经常会用到节流,比如,input的输入,滚动条监听等等,而且对节流和防抖的概念很模糊,所以在这里简单的写了一下这两个函数便于理解

    防抖

    就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。节流在input输入时最常用

    /** 防抖函数 */
    const debounce = (fn: (...args), timeout) => {
      let timer
      return (...args) => {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {fn(...args)}, timeout);
      }
    }

    节流

    就是指连续触发事件但是在 n 秒中只执行一次函数。简单说就是会使函数执行的频率不那么频繁

    防抖函数的方法有两种

    方法一:时间戳

    const throttle=(func, wait)=> {
        let previous = 0;
        return ()=> {
            let now = Date.now();if (now - previous > wait) {
                func();
          previous
    = now;
    } } }

    方法二:定时器

    const throttle=(func, wait)=> {
        let timeout;
        return ()=> {
            if (!timeout) {
                timeout = setTimeout(() => {
                    timeout = null;
                    func()
                }, wait)
            }
    
        }
    }
  • 相关阅读:
    测试打印功能
    绘图
    图片验证码
    图片防盗
    图片水印
    surface 译
    ViewManager 译
    WindowId 译
    Display
    LayoutParams
  • 原文地址:https://www.cnblogs.com/zienlove/p/15184287.html
Copyright © 2011-2022 走看看