npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@zgm-npm/task-limiter

v1.0.2

Published

A lightweight library for controlling concurrent tasks with priority scheduling, timeout, and retry mechanisms.

Readme

🚀 并发任务控制库 - 从痛点出发,打造极致性能!

🔥 传统痛点

在高并发场景下(如大屏开发、数据可视化),开发者常遇到以下问题:

  1. 后端崩溃:同时发送 10+ 接口请求,后端负载激增,响应时间超过 40 秒。
  2. 资源浪费:低优先级任务阻塞高优先级任务,用户体验差。
  3. 无重试机制:网络波动导致任务失败,需手动处理。

💡 设计初衷

为解决这些问题,我们开发了并发控制器,旨在:

  • 智能调度:动态分配资源,优先执行高优先级任务。
  • 负载保护:限制并发数,避免后端过载。
  • 自动重试:任务失败时自动重试,提升稳定性。

🌟 宣传亮点

  • ⚡ 极致性能:智能任务调度算法,轻松应对 1000+ 并发任务,后端再也不会被卡爆!
  • 🎛️ 灵活配置:支持动态调整并发数、自定义优先级、超时和重试策略,满足你的所有想象!
  • 🛠️ 开箱即用:简洁的 API 设计,5 分钟快速集成到任何项目,Vue、React 通吃!
  • 📊 数据为王:内置性能监控,实时展示任务执行状态,优化效果一目了然!

📦 安装指南

npm install @zgm-npm/task-limiter
# 或
pnpm add @zgm-npm/task-limiter
# 或
yarn add @zgm-npm/task-limiter

🎯 使用教程

原生 JavaScript 示例

基础用法

const { TaskLimiter } = require('@zgm-npm/task-limiter');
const limiter = new TaskLimiter({ maxConcurrent: 5 });

// 添加高优先级任务
limiter.addTask({
  task: () => fetch('https://api.example.com/data'),
  priority: 1, // 优先级越高,越先执行
  timeout: 3000, // 超时时间(毫秒)
  retry: 2, // 失败重试次数
});

// 添加低优先级任务
limiter.addTask({
  task: () => fetch('https://api.example.com/logs'),
  priority: 3,
  timeout: 5000,
});

addTaskrun 的区别

| 特性 | addTask | run | |---------------------|------------------------------------|------------------------------------| | 任务添加方式 | 逐个添加 | 批量添加 | | 优先级控制 | 支持单独设置 | 不支持 | | 超时/重试配置 | 支持单独设置 | 不支持 | | 适用场景 | 动态任务队列 | 固定任务列表 | | 返回值 | 无(任务加入队列) | 返回所有任务的结果数组 |

addTask 示例

const limiter = new TaskLimiter({ maxConcurrent: 2 });

// 动态添加高优先级任务
limiter.addTask({
  task: () => fetchUsers(),
  priority: 1,
  timeout: 3000,
});

// 动态添加低优先级任务
limiter.addTask({
  task: () => fetchTasks(),
  priority: 3,
});

run 示例

const limiter = new TaskLimiter({ maxConcurrent: 2 });

// 批量执行任务
const results = await limiter.run([
  () => fetchUsers(),
  () => fetchTasks(),
  () => fetchStats(),
]);
console.log(results);

run 方法详解

run 方法是并发控制器的核心功能,用于批量执行任务并智能调度。以下是其核心特性和使用方式:

功能

  • 批量执行:接受一个任务数组,按配置的并发数执行。
  • 智能调度:根据任务优先级和延迟动态调整执行顺序。
  • 结果聚合:返回所有任务的执行结果,顺序与输入数组一致。

参数

limiter.run(tasks: Array<() => Promise<any>>): Promise<Array<any>>
  • tasks:任务数组,每个任务是一个返回 Promise 的函数。

返回值

  • 返回一个 Promise,解析值为所有任务的执行结果数组。

示例

// 定义任务
const tasks = [
  () => fetch('https://api.example.com/users'),
  () => fetch('https://api.example.com/tasks'),
  () => fetch('https://api.example.com/stats'),
];

// 执行任务
const results = await limiter.run(tasks);
console.log(results); // [users, tasks, stats]

对比 Promise.all

| 特性 | limiter.run | Promise.all | |---------------------|---------------------|---------------------| | 并发控制 | ✅ 支持 | ❌ 不支持 | | 优先级调度 | ✅ 支持 | ❌ 不支持 | | 超时重试 | ✅ 支持 | ❌ 不支持 | | 后端负载保护 | ✅ 支持 | ❌ 不支持 |

完整 HTML 示例

以下是一个完整的 HTML 文件示例,展示如何在浏览器中直接使用并发控制器:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>并发控制器测试</title>
</head>
<body>
    <script src="./dist/bundle.iife.js"></script>
    <script type="module">
        import mockData from './mockData.js';

        const limiter = new window.taskLimiter.TaskLimiter(2); // 最大并发数为 2

        // 模拟接口函数
        function fetchUsers() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve(mockData.api1.response);
                }, 5000);
            });
        }

        function fetchTasks() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve(mockData.api2.response);
                }, 500);
            });
        }

        function createUser() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve(mockData.api3.response);
                }, 1500);
            });
        }

        function updateTask() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve(mockData.api4.response);
                }, 4000);
            });
        }

        function deleteUser() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve(mockData.api5.response);
                }, 800);
            });
        }

        function fetchStats() {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve(mockData.api6.response);
                }, 300);
            });
        }

        // 使用并发控制器运行所有任务
        async function run() {
            const results = await limiter.run([
                fetchUsers,
                fetchTasks,
                createUser,
                updateTask,
                deleteUser,
                fetchStats,
            ]);
            console.log("所有任务执行结果:", results);
        }

        run();
    </script>
</body>
</html>

说明

  • 并发控制:通过 TaskLimiter(2) 限制同时运行的任务数为 2,避免后端过载。
  • 任务调度:高延迟任务(如 fetchUsers)和低延迟任务(如 fetchStats)会被智能调度,确保资源合理分配。
  • 结果输出:所有任务完成后,结果会通过 console.log 输出。

Vue 示例

<template>
  <div>
    <button @click="fetchData">加载数据</button>
    <div v-if="loading">加载中...</div>
    <div v-else>{{ data }}</div>
  </div>
</template>

<script>
import { TaskLimiter } from '@zgm-npm/task-limiter';

export default {
  data() {
    return {
      data: null,
      loading: false,
      limiter: new TaskLimiter({ maxConcurrent: 3 }),
    };
  },
  methods: {
    async fetchData() {
      this.loading = true;
      try {
        await this.limiter.addTask({
          task: async () => {
            const res = await fetch('https://api.example.com/data');
            this.data = await res.json();
          },
          priority: 1,
        });
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

React 示例

import React, { useState } from 'react';
import { TaskLimiter } from '@zgm-npm/task-limiter';

const limiter = new TaskLimiter({ maxConcurrent: 3 });

export default function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    try {
      await limiter.addTask({
        task: async () => {
          const res = await fetch('https://api.example.com/data');
          setData(await res.json());
        },
        priority: 1,
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <button onClick={fetchData}>加载数据</button>
      {loading ? <div>加载中...</div> : <div>{JSON.stringify(data)}</div>}
    </div>
  );
}

📈 性能对比

| 场景 | 优化前加载时间 | 优化后加载时间 | |------|----------------|----------------| | 10 个接口并发 | 40+ 秒 | 2 秒 | | 50 个接口并发 | 后端崩溃 | 5 秒 |

🔧 API 文档

  • TaskLimiter(options):初始化任务控制器。
    • maxConcurrent:最大并发数(默认:5)。
    • timeout:全局任务超时时间(默认:5000 毫秒)。
  • addTask(taskConfig):添加任务到队列。
    • task:任务函数(必须返回 Promise)。
    • priority:优先级(数字越小优先级越高)。
    • timeout:任务超时时间(覆盖全局设置)。
    • retry:失败重试次数(默认:0)。

🤝 贡献指南

欢迎提交 Pull Request 或 Issue,一起打造更强大的并发控制器!

📜 许可证

MIT