当前位置:首页 > JavaScript

js实现防洪

2026-01-14 14:07:49JavaScript

防抖(Debounce)实现

防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。

function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

// 使用示例
const input = document.getElementById('search-input');
input.addEventListener('keyup', debounce(function() {
  console.log('Searching for:', input.value);
}, 500));

节流(Throttle)实现

节流的核心思想是在固定时间间隔内只执行一次回调函数。适用于滚动事件、鼠标移动等高频触发场景。

function throttle(func, limit) {
  let inThrottle;
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// 使用示例
window.addEventListener('scroll', throttle(function() {
  console.log('Scrolling...');
}, 1000));

请求限流(Rate Limiting)

对于API请求,可通过令牌桶算法实现限流,控制单位时间内的请求数量。

class RateLimiter {
  constructor(limit, interval) {
    this.limit = limit;
    this.interval = interval;
    this.queue = [];
    this.tokens = limit;
    setInterval(() => this.refillTokens(), interval);
  }

  refillTokens() {
    this.tokens = Math.min(this.limit, this.tokens + 1);
    this.processQueue();
  }

  processQueue() {
    while (this.tokens > 0 && this.queue.length > 0) {
      const request = this.queue.shift();
      this.tokens--;
      request.resolve(request.fn());
    }
  }

  enqueue(fn) {
    return new Promise((resolve) => {
      this.queue.push({ fn, resolve });
      this.processQueue();
    });
  }
}

// 使用示例
const limiter = new RateLimiter(5, 1000); // 每秒5次请求
async function makeRequest() {
  return limiter.enqueue(() => fetch('https://api.example.com'));
}

批量处理(Batching)

对于高频触发的事件(如实时日志),可通过批量处理减少操作次数。

js实现防洪

function createBatcher(processBatch, batchSize = 10, timeout = 1000) {
  let batch = [];
  let timer = null;

  function flush() {
    processBatch([...batch]);
    batch = [];
    clearTimeout(timer);
    timer = null;
  }

  return function(item) {
    batch.push(item);
    if (batch.length >= batchSize) {
      flush();
    } else if (!timer) {
      timer = setTimeout(flush, timeout);
    }
  };
}

// 使用示例
const logBatcher = createBatcher((logs) => {
  console.log('Batch logs:', logs);
});
document.addEventListener('click', (e) => logBatcher(e.target));

注意事项

  • 防抖和节流的区别:防抖在连续触发时只执行最后一次,节流在固定间隔执行。
  • 请求限流需考虑分布式环境下的同步问题,单机方案可使用Redis等中间件扩展。
  • 批量处理的超时时间和批次大小需根据实际场景调整。

标签: js
分享给朋友:

相关文章

js实现vue

js实现vue

Vue.js 的基本实现方法 在 JavaScript 中实现 Vue.js 的功能,可以通过直接引入 Vue 库或使用现代构建工具(如 Vite 或 Webpack)。以下是几种常见的实现方式:…

js实现动画

js实现动画

使用 CSS 动画与 JavaScript 控制 通过 JavaScript 动态添加或移除 CSS 类来触发动画。CSS 定义关键帧(@keyframes),JavaScript 通过 classL…

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现选项卡

js实现选项卡

实现选项卡的基本思路 选项卡通常由一组标签和对应的内容面板组成。点击标签时,显示对应的内容面板,隐藏其他面板。实现这一效果需要结合HTML结构、CSS样式和JavaScript交互逻辑。 HTML结…