JS--函数节流+函数防抖

一、函数节流

某函数在指定时间间隔内执行,如:每1秒执行一次

1、第一次就执行
// 对函数进行 节流
function throttle (fn,  delay = 1000) {
    let timer = null;
    let firstTime = true;

    return function (...args) {
        if (firstTime) {
          // 第一次加载
            fn.apply(this, args);
            return firstTime = false;
        }
        if (timer) {
          // 定时器正在执行中,跳过
            return;
        }
        timer = setTimeout(() => {
            clearTimeout(timer);
            timer = null;
            fn.apply(this, args);
        },  delay);
    };
}
// 需要被节流的 函数
function scrollHandler (arg) {
    console.log(`${arg}--被执行了`);
}
// 被节流的函数 -- 节流限制: 每 1000 毫秒执行一次
const throttleFunc = throttle(scrollHandler, 1000);
let i = 0;
// 模拟 页面滚动事件
const interval = setInterval(() => {
    console.log(`${i} --- 进来了,但是没有执行`);
    throttleFunc(i++);
}, 10);
2、首次不执行,需等待delay时间后才能执行第一次
function throttle(fn,  delay = 1000) {
  let prevTime = Date.now();
  return function () {
    let curTime = Date.now();
    if (curTime - prevTime > delay) {
      fn.apply(this, arguments);
      prevTime = curTime;
    }
  };
}
// 需要被节流的 函数
function scrollHandler (arg) {
    console.log(`${arg}--被执行了`);
}
// 被节流的函数 -- 节流限制: 每 1000 毫秒执行一次
const throttleFunc = throttle(scrollHandler, 1000);
let i = 0;
// 模拟 页面滚动事件
const interval = setInterval(() => {
    console.log(`${i} --- 进来了,但是不知道有没有执行`);
    throttleFunc(i++);
}, 10);

##二、函数防抖

当持续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。
就像游戏里放技能时需要读条一样,读条结束才能放出技能,但是在读条结束前,你又按了一次技能,那么只能重新读条。

function debounce(func, delay) {
  let timeout;
  return function() {
    let context = this; // 指向全局
    let args = arguments;
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      func.apply(context, args); // context.func(args)
    }, delay);
  };
}
// 使用
window.onscroll = debounce(function() {
  console.log('debounce');
}, 1000);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值