uniapp防抖节流封装 您所在的位置:网站首页 防抖函数封装图怎么看 uniapp防抖节流封装

uniapp防抖节流封装

2024-06-02 15:05| 来源: 网络整理| 查看: 265

在防抖这一块,可以防止用户多次快速点击造成不必要的错误,基本原理是加个延时器,在时间到来前再次点击将重新计时。采用闭包实现变量不被销毁。具体代码如下:

//方法 export const Debounce = (fn, t) => { let delay = t || 500; return function () { let args = arguments; let timer1 = null // console.log(timer1); if(timer1){ clearTimeout(timer1); } timer1 = setTimeout(() => { fn.apply(this, args); timer1 = null; }, delay); } }; //调用 /*import {Debounce} from '@/common/debounceThrottle.js' Debounce(() => { //要执行的函数 }, 200)() */

但我在实际使用中有个问题,timer在每次调用后就被销毁了,每次点击 timer都会重新被赋值为 null 。最终效果只剩了延迟触发,点几次,触发几次。研究了很久都没找到原因,最后,我采用了取巧的方法,将timer提到外面,定义为全局变量。虽然效果是达到了,但之前的问题仍不知道是哪里出了问题,希望有大佬能解惑。 下面是我取巧的方法:

/** * 函数防抖 (只执行最后一次点击) * @param fn * @param delay * @returns {Function} * @constructor */ let timer1 = null; //防抖, let timer2 = null; //节流 export const Debounce = (fn, t) => { let delay = t || 500; return function () { let args = arguments; // let timer1 = null // console.log(timer1); if(timer1){ clearTimeout(timer1); } timer1 = setTimeout(() => { fn.apply(this, args); timer1 = null; }, delay); } }; // 使用 /*import {Debounce} from '@/common/debounceThrottle.js' Debounce(() => { //要执行的函数 }, 200)() */ /** * 函数节流 * @param fn * @param interval * @returns {Function} * @constructor */ export const Throttle = (fn, t) => { let last; let interval = t || 500; return function () { let args = arguments; let now = +new Date(); if (last && now - last < interval) { clearTimeout(timer2); timer2 = setTimeout(() => { last = now; fn.apply(this, args); }, interval); } else { last = now; fn.apply(this, args); } } };


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有