...
大前端

奇特的一个需求,在指定时间内随机间隔跑完指定的步数,使用js实现方法

前言

这是一个很奇特的需求
在指定的是个时间内
使用随机步数,跑完指定数量的回调。
听起来可能比较绕口
那么这个函数它有什么用呢

用途

红包雨:假设有1000个红包需要在60秒内下完
随机请求:假设有10个请求,需要在10分钟内做完,并且间隔时间随机。
...
用途还是很广的,看你需求了。

代码

function generateWithCallback(count, totalTime, callback) {
    if (typeof callback !== "function") {
        throw new Error("Callback must be a function");
    }

    const intervals = [];
    let sum = 0;

    // 1. 生成随机间隔比例
    for (let i = 0; i < count; i++) {
        const rand = Math.random();
        intervals.push(rand);
        sum += rand;
    }

    // 2. 归一化比例到总时间
    for (let i = 0; i < intervals.length; i++) {
        intervals[i] = (intervals[i] / sum) * totalTime;
    }

    let currentIndex = 0; // 当前回调索引
    let isPaused = false; // 控制是否暂停
    let timeoutId = null; // 保存当前的 `setTimeout` ID,用于清理或控制

    const triggerCallback = () => {
        if (currentIndex < count && !isPaused) {
            callback(currentIndex); // 调用回调函数,传入当前索引
            const nextInterval = intervals[currentIndex];
            currentIndex++;
            timeoutId = setTimeout(triggerCallback, nextInterval); // 等待下一个随机间隔
        }
    };

    // 提供暂停和恢复方法
    return {
        start() {
            if (!isPaused) {
                triggerCallback();
            }
        },
        pause() {
            isPaused = true;
            if (timeoutId) {
                clearTimeout(timeoutId); // 停止当前的 `setTimeout`
                timeoutId = null;
            }
        },
        resume() {
            if (isPaused) {
                isPaused = false;
                triggerCallback(); // 恢复从当前索引继续
            }
        },
    };
}

// 使用示例
const generator = generateWithCallback(
    10, // 生成 10 次回调
    60000, // 总时间(1分钟)
    (index) => {
        console.log(`Callback at index: ${index}`);
    }
);

// 启动生成
generator.start();

// 暂停和恢复示例
setTimeout(() => {
    console.log("Pausing...");
    generator.pause();
}, 15000); // 15秒后暂停

setTimeout(() => {
    console.log("Resuming...");
    generator.resume();
}, 30000); // 30秒后恢复

拿走不谢~

前端JS使用Zip打包下载 go golang 配置国内源,解决go get卡住
biu biu biu
Navicat Premium 15破解 windows Navicat Premium 注册出现 Rsa Public Key not Find... Uninstall Tool 绿色版下载 微信网页版发送消息代码 windows cmd控制台隐藏运行 thinkphp 伪静态 NGINX IIS Apache