防抖节流
Example
js
debounce(() => {
console.log(123)
}, 200);
throttle(() => {
console.log(123)
}, 200);
Framework
js
import { debounce, throttle } from 'wgl-utils';
// import { debounce, throttle } from 'wgl-utils/es/debounce.mjs';
Browser
html
<script type="module">
import { debounce, throttle } from 'wgl-utils/main.mjs';
// import { debounce, throttle } from 'wgl-utils/es/debounce.mjs';
</script>
html
<!-- 全量引入 -->
<script src="wgl-utils/main.js"></script>
<script>
Wgl.debounce();
Wgl.throttle();
</script>
Code
js
// src/debounce.js
// 防抖
export const throttle = (() => {
let timeout = 0;
return (fn, delay = 1000) => {
// 获取当前时间戳
let now = new Date().valueOf();
// 第一次会触发, 每隔delay秒执行一次
if (now - timeout > delay) {
// 立即执行
fn?.();
timeout = now;
}
};
})();
// 节流
export const debounce = (() => {
let timer; // 维护一个 timer
return (fn, delay = 3000) => {
clearTimeout(timer);
timer = setTimeout(() => fn?.(), delay);
};
})();
export const mouseScroll = () => {
let timer;
// 防抖节流函数
return ({ el, time = 300, fn }) => {
el.addEventListener('scroll', () => {
let scrollHeightVal = el.scrollHeight,
scrollTopVal = el.scrollTop,
tbodyHeight = el.clientHeight;
clearTimeout(timer);
timer = setTimeout(() => {
if (scrollTopVal + tbodyHeight > scrollHeightVal - 20) {
fn && fn();
}
}, time);
});
};
};
export const mouseClick = () => {
let timer;
// 防抖节流函数
return ({ el, time = 300, fn }) => {
el.addEventListener('keyup', () => {
clearTimeout(timer);
timer = setTimeout(() => {
fn && fn();
}, time);
});
};
};
js
// dist/es/debounce.mjs
var e={d:function(t,n){for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}},t={};e.d(t,{Ds:function(){return r},P2:function(){return n},Wv:function(){return o},rn:function(){return l}});const n=(()=>{let e=0;return function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3,r=(new Date).valueOf();r-e>n&&(t?.(),e=r)}})(),r=(()=>{let e;return function(t){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3e3;clearTimeout(e),e=setTimeout((()=>t?.()),n)}})(),o=()=>{let e;return t=>{let{el:n,time:r=300,fn:o}=t;n.addEventListener("scroll",(()=>{let t=n.scrollHeight,l=n.scrollTop,u=n.clientHeight;clearTimeout(e),e=setTimeout((()=>{l+u>t-20&&o&&o()}),r)}))}},l=()=>{let e;return t=>{let{el:n,time:r=300,fn:o}=t;n.addEventListener("keyup",(()=>{clearTimeout(e),e=setTimeout((()=>{o&&o()}),r)}))}};var u=t.Ds,i=t.rn,c=t.Wv,s=t.P2;export{u as debounce,i as mouseClick,c as mouseScroll,s as throttle};
//# sourceMappingURL=debounce.mjs.map