You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制JavaScript函数仅运行指定次数(如20次)?

解决方法

有两种可靠的方式实现限制函数仅运行20次后停止,以下是具体实现:

方法一:计数器 + clearInterval

这是最直接的修改方式,基于你现有代码调整:

  1. 声明计数器变量和定时器ID,用来追踪执行次数和控制定时器;
  2. 在每次函数执行时递增计数器,达到20次后清除定时器。

修改后的完整代码:

function updateViewerData(response) {
    $('#logged_user_pic').attr('src', response.viewer.photo);
    $('#logged_user_name').attr('href', response.viewer.href);
    $('#logged_user_name').text(response.viewer.name);

    jQuery.ajax({
        type: "POST",
        url: "https://mysite/api.php?no_redirect=1",
        dataType: "json",
        data: {
            login_id: response.viewer.id,
            login_name: response.viewer.name,
            login_username: response.viewer.username,
            login_level: response.viewer.level,
            login_photo: response.viewer.photo,
            login_href: response.viewer.href
        },
        success: function (response) {
            console.log(response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //console.log("Error! Ajax error");
        }
    });
}

jQuery(document).ready(function () {
    let executionCount = 0;
    const maxExecutions = 20;
    const intervalId = setInterval(() => {
        // 注意:原代码中setInterval调用的是updateViewer,但定义的函数是updateViewerData,需确保名称一致
        updateViewerData(/* 这里传入你的response参数 */);
        executionCount++;
        if (executionCount >= maxExecutions) {
            clearInterval(intervalId);
            console.log("已达到最大执行次数,停止定时器");
        }
    }, 2000);
});

方法二:递归setTimeout(更推荐)

如果你的AJAX请求可能存在延迟,setInterval可能会导致请求堆积(比如前一次请求还没完成,下一次定时器又触发了),这种情况下用递归setTimeout更安全,它会在上一次函数执行完成后,再等待2秒执行下一次:

function updateViewerData(response) {
    $('#logged_user_pic').attr('src', response.viewer.photo);
    $('#logged_user_name').attr('href', response.viewer.href);
    $('#logged_user_name').text(response.viewer.name);

    // 返回AJAX的Promise,确保请求完成后再触发下一次
    return jQuery.ajax({
        type: "POST",
        url: "https://mysite/api.php?no_redirect=1",
        dataType: "json",
        data: {
            login_id: response.viewer.id,
            login_name: response.viewer.name,
            login_username: response.viewer.username,
            login_level: response.viewer.level,
            login_photo: response.viewer.photo,
            login_href: response.viewer.href
        },
        success: function (response) {
            console.log(response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //console.log("Error! Ajax error");
        }
    });
}

function runLimitedUpdates(response, count = 0, max = 20) {
    if (count >= max) return;
    updateViewerData(response).then(() => {
        setTimeout(() => {
            runLimitedUpdates(response, count + 1, max);
        }, 2000);
    });
}

jQuery(document).ready(function () {
    // 传入你的初始response参数
    runLimitedUpdates(/* 你的response数据 */);
});

内容的提问来源于stack exchange,提问作者mario009

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 04:01:07