时间的节流防抖-多用于单击事件-一段时间内防止连续触发

作者: 小枫枫

临枫的项目经历分享给你们啦~

扫码交朋友

标签:

特别声明:文章有少部分为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!

 

普通使用:
/**
 * @param { fn   } ---->执行的函数
 * @param { debounce    } ---->特定时间内防止重复点击 默认500毫秒
 * @description 
 */
let timer, bool;
function throttle(fn, debounce = 500) {
	if (!bool) {
		bool = true;
		typeof fn === 'function' && fn();
		timer = setTimeout(() => {
			bool = false;
			clearTimeout(timer)
		}, debounce);
	}
};
//使用:
function click(){
        throttle(()=> {
	        console.log("有本事连续点击我啊")
        }, 1000);
}

//作为js模块:

let timer, bool;
function throttle(fn, debounce = 500, immediate = true) {
	if (!bool) {
		bool = true;
		typeof fn === 'function' && fn();
		timer = setTimeout(() => {
			bool = false;
			clearTimeout(timer)
		}, debounce);
	}
};
export default throttle



//ts
export function throttle(fn:(...args:any []) => any,delay:number){
    let timer:ReturnType<typeof setTimeout> | null = null,last:number = 0;
    return function<T>(this:(...args:any []) => any,...args:Array<T>) {
        let now = +new Date();
        if(last && now < last + delay){
            clearTimeout(timer);
            timer = setTimeout(() => {
                last = now;
                fn.apply(this,args);
            },delay);
        }else{
            last = now;
            fn.apply(this,args);
        }
    }
}
本文最后更新于2020-9-12,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
分享到:
打赏

作者: 小枫枫, 转载或复制请以 超链接形式 并注明出处 小枫枫不疯喔
原文地址: 《时间的节流防抖-多用于单击事件-一段时间内防止连续触发》 发布于2020-9-12

评论

切换注册

登录

您也可以使用第三方帐号快捷登录

切换登录

注册

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏