[JS工具]流输出缓冲池

21 阅读1分钟

[JS工具]流输出缓冲池

OutputBuffer 是一个用于控制输出频率的类,通过动态调整输出间隔,避免输出过于频繁或集中。它支持动态调整间隔、添加数据、开始、结束和停止输出流程等功能,并提供 onOutputonFinish 回调函数,方便在数据输出和处理完毕时执行自定义操作。

/**
 * 流输出缓冲
 */
class OutputBuffer {
  constructor({ minInterval = 20, maxInterval = 500, onOutput, onFinish } = {}) {
    this.buffer = []
    this.isEnd = false
    this.minInterval = minInterval
    this.maxInterval = maxInterval
    this.onOutput = onOutput || (() => {})
    this.onFinish = onFinish || (() => {})
    this.timer = null
  }

  getCurrentInterval() {
    if (this.isEnd || this.buffer.length > 100) {
      return this.minInterval
    } else if (this.buffer.length < 10) {
      return this.maxInterval
    } else {
      // 10-100 之间,线性插值从 max 到 min
      const range = 100 - 10
      const pos = this.buffer.length - 10
      const ratio = pos / range
      return Math.round(this.maxInterval - ratio * (this.maxInterval - this.minInterval))
    }
  }

  processNext() {
    this.timer = null
    if (this.buffer.length > 0) {
      const data = this.buffer.shift()
      console.log('缓冲池输出,剩余长度:', this.buffer.length)
      this.onOutput(data)
      const delay = this.getCurrentInterval()
      this.timer = setTimeout(() => this.processNext(), delay)
    } else if (this.isEnd) {
      this.onFinish()
    }
  }

  start() {
    if (!this.timer) {
      this.processNext()
    }
  }

  add(data) {
    this.buffer.push(data)
    this.start()
  }

  end() {
    this.isEnd = true
    this.start()
  }

  // Optional: to stop manually if needed
  stop() {
    if (this.timer) {
      clearTimeout(this.timer)
      this.timer = null
    }
  }
}

export default OutputBuffer