节流 防抖函数

150 阅读1分钟

前端开发中会用的节流函数, 防抖函数。 防抖函数就是在一定时间重复执行一件事情,让他只执行最后一次的操作, 节流函数是在一定时间内重复执行一件事情,他只会执行第一次的操作。

防抖函数

//函数的延时器
let debounceTimer: any = null; 

//防抖函数  fn 需要执行的方法   delay 防抖函数的时间
const debounce = (fn: () => void, delay: number) => {

//判断debounceTimer是否有值,如果有值就清楚延时器
    if(debounceTimer){
        clearTimeout(debounceTimer);
    }
    //给延时器赋值做一个延时任务
    debounceTimer = setTimeout(() => {
        fn();
    }, delay);

};

这个是ts集合写的,不需要的ts的可以去掉变量类型。

let debounceTimer = null; 
let throttleTimer = true;

let num = 0;
const debounce = (fn, delay) => {

    if(debounceTimer){
        clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(() => {
        fn();
    }, delay);

};

debounce(() => {
coneole.log('防抖函数调用');
}, 1000);

以上就是一个简单的防抖函数;

节流函数

let throttleTimer = true;

// 节流函数  执行一次后一段时间不让期执行
const throttle = (fn: () => void, delay: number) => {
    if(!throttleTimer){
        return false;
    }
    throttleTimer = false;
    setTimeout(() => {
        fn();
        throttleTimer = true;
    }, delay);

};