首页 > 其他 > 详细

节流和防抖简单介绍

时间:2021-08-25 12:37:55      阅读:12      评论:0      收藏:0      [点我收藏+]

前言

因为在开发过程中经常会用到节流,比如,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)
        }

    }
}

 

节流和防抖简单介绍

原文:https://www.cnblogs.com/zienlove/p/15184287.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!