当前位置:首页 > 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)

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

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
分享给朋友:

相关文章

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现打印

js实现打印

使用window.print()方法实现打印 在JavaScript中,可以通过调用window.print()方法直接触发浏览器的打印功能。这会打开系统的打印对话框,用户可以选择打印机和设置打印选项…

js 实现分页

js 实现分页

实现分页的基本逻辑 分页功能通常需要后端返回数据总量或总页数,前端根据当前页码和每页条数截取对应数据。以下是一个基于JavaScript的简单分页实现方案: 前端分页实现 假设已有从后端获取的完整数…

js实现论坛

js实现论坛

实现论坛的基本功能 使用JavaScript实现一个论坛需要结合前端和后端技术。前端可以使用React、Vue或Angular等框架,后端可以选择Node.js配合Express或Koa框架。数据库可…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue…

js实现吸色

js实现吸色

使用Canvas实现吸色功能 通过Canvas的getImageData方法获取像素颜色数据。创建一个Canvas元素,将目标图像绘制到Canvas上,通过鼠标事件获取坐标对应的颜色值。 cons…