当前位置:首页 > JavaScript

js 实现一个任务队列

2026-01-31 10:07:24JavaScript

实现基础任务队列结构

使用数组存储任务,通过push方法添加任务,shift方法取出任务执行:

class TaskQueue {
  constructor() {
    this.tasks = [];
    this.isRunning = false;
  }

  add(task) {
    this.tasks.push(task);
    if (!this.isRunning) this.run();
  }

  async run() {
    this.isRunning = true;
    while (this.tasks.length > 0) {
      const task = this.tasks.shift();
      try {
        await task();
      } catch (error) {
        console.error('Task error:', error);
      }
    }
    this.isRunning = false;
  }
}

添加并发控制功能

扩展基础队列实现最大并发数限制:

js 实现一个任务队列

class ConcurrentQueue {
  constructor(concurrency = 1) {
    this.tasks = [];
    this.concurrency = concurrency;
    this.running = 0;
  }

  add(task) {
    this.tasks.push(task);
    this.next();
  }

  next() {
    while (this.running < this.concurrency && this.tasks.length) {
      const task = this.tasks.shift();
      this.running++;
      task().finally(() => {
        this.running--;
        this.next();
      });
    }
  }
}

实现优先级队列

通过优先级参数控制任务执行顺序:

class PriorityQueue {
  constructor() {
    this.highPriority = [];
    this.lowPriority = [];
    this.isRunning = false;
  }

  add(task, priority = 'low') {
    const queue = priority === 'high' ? this.highPriority : this.lowPriority;
    queue.push(task);
    if (!this.isRunning) this.run();
  }

  async run() {
    this.isRunning = true;
    while (this.highPriority.length || this.lowPriority.length) {
      const queue = this.highPriority.length ? this.highPriority : this.lowPriority;
      const task = queue.shift();
      try {
        await task();
      } catch (error) {
        console.error('Task error:', error);
      }
    }
    this.isRunning = false;
  }
}

带错误恢复的队列实现

增加错误重试机制和失败回调:

js 实现一个任务队列

class ResilientQueue {
  constructor(maxRetries = 3) {
    this.tasks = [];
    this.maxRetries = maxRetries;
  }

  add(task, onError = null) {
    this.tasks.push({ task, retries: 0, onError });
    if (this.tasks.length === 1) this.run();
  }

  async run() {
    while (this.tasks.length) {
      const current = this.tasks[0];
      try {
        await current.task();
        this.tasks.shift();
      } catch (error) {
        current.retries++;
        if (current.retries >= this.maxRetries) {
          if (current.onError) current.onError(error);
          this.tasks.shift();
        }
      }
    }
  }
}

使用示例

基础队列使用方式:

const queue = new TaskQueue();
queue.add(() => new Promise(resolve => {
  setTimeout(() => {
    console.log('Task 1 done');
    resolve();
  }, 1000);
}));
queue.add(() => console.log('Task 2'));

并发队列示例:

const concurrent = new ConcurrentQueue(2);
for (let i = 1; i <= 5; i++) {
  concurrent.add(() => new Promise(resolve => {
    setTimeout(() => {
      console.log(`Task ${i} completed`);
      resolve();
    }, 1000);
  }));
}

标签: 队列任务
分享给朋友:

相关文章

php队列的实现

php队列的实现

PHP队列的实现方式 PHP中实现队列功能可以通过多种方式,根据需求选择适合的方案: 使用数组实现基础队列 PHP数组本身支持队列操作,利用array_push和array_shift函数:…

php 实现队列

php 实现队列

PHP 实现队列的方法 PHP 可以通过多种方式实现队列功能,以下是几种常见的实现方法: 使用数组实现队列 PHP 数组可以通过 array_push 和 array_shift 函数模拟队列的先进…

vue实现队列消息

vue实现队列消息

Vue 实现队列消息 在 Vue 中实现队列消息功能,可以通过以下方法实现一个简单的消息队列系统,用于显示和管理临时通知(如成功、错误提示)。 使用 Vuex 管理消息队列 创建一个 Vuex st…

vue实现定时任务

vue实现定时任务

实现定时任务的几种方法 在Vue中实现定时任务可以通过多种方式,以下是几种常见的实现方法: 使用setInterval 在Vue组件的mounted生命周期钩子中设置setInterval,在bef…

vue任务表单实现指南

vue任务表单实现指南

Vue 任务表单实现方法 表单基础结构 使用 Vue 的 v-model 实现数据双向绑定,创建任务表单的基础结构: <template> <form @submit.pre…

react如何确定任务优先级

react如何确定任务优先级

React 任务优先级机制 React 使用 Fiber 架构来管理任务优先级,通过Lane 模型(React 18+)或Expiration Time(旧版)实现优先级调度。以下是核心机制:…