| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- let timer1 = null; //防抖,
- let timer2 = null; //节流
- function 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)() */
- function 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);
- }
- }
- }
-
- module.exports = {
- Debounce: Debounce,
- Throttle: Throttle
- }
|