如何运行一个循环并在破坏前最多尝试10次的setInterval?

时间:2012-04-17 00:02:43

标签: javascript jquery

我有以下内容尝试重新加载连接drop:

setInterval(window.location.reload(), 1000);

我对此的关注是,它可以永远持续下去,为我的申请做好准备。

如何更新以上内容,在放弃和破坏前最多尝试20次?

谢谢

3 个答案:

答案 0 :(得分:2)

这让我觉得很脏,但你可以在每次刷新时更新/解压缩窗口哈希:

function hack () {
  var last = parseInt(location.hash.slice(1));
  if (last < 20) {
    window.location.hash = last + 1;
    window.location.reload();
  }
}

window.location.hash = 0;
setTimeout(hack, 1000);

答案 1 :(得分:1)

您需要将一些计数器状态从一个页面加载到下一个加载,这样您就可以知道何时完成了20次重新加载。您的选择是:

  1. 哈希值
  2. 查询参数
  3. Cookie值
  4. 存储在本地存储中的内容
  5. 如果您不需要此值继续超出此页面的重新加载,则选项1)和2)更好,因为它们只是您需要的持久性。哈希值不会发送到您的服务器,但可能会干扰哈希值的其他用途。查询参数将被发送到服务器,但任何合理的服务器都将忽略它不知道的查询值,并且它不会干扰其他任何事情。我可能会选择一个查询参数,实际上已经使用了一个来避免我的一些代码中的无限重定向循环。你可以像这样实现选项2):

    function checkAutoReload() {
        var currentCnt = 0;
        var re = /(\?|&)(reloadCnt=)(\d+)/;
        var param = window.location.search.match(re), newURL;
        if (param) {
            currentCnt = parseInt(param[3], 10);
            newURL = window.location.href.replace(re, "$1$2" + (currentCnt + 1))
        } else {
            newURL = window.location.href;
            newURL += window.location.search ? "&" : "?";
            newURL += "reloadCnt=1";
        }
        if (currentCnt < 20) {
            window.location.replace(newURL);
        }
    }
    
    setTimeout(checkAutoReload, 1000);
    

    请注意,不需要setInterval(),因为给定页面的代码在重新加载或发现重新加载之前只运行一次。

答案 2 :(得分:0)

将reloadCount存储在localStorage

MDN DOM Storage

    var maxReload = 20;
    var reloadPage = function() {
        if (typeof a !== "undefined" && a !== null) {
            console.log(localStorage.reloadCount);
            localStorage.reloadCount = 0;
        };
        var reloadCount = parseInt(localStorage.reloadCount, 10);
        console.log(reloadCount);
        if (reloadCount < maxReload) {
            reloadCount += 1;
            localStorage.reloadCount = reloadCount;

            // RELOAD CODE HERE
        };
    };

    // call reloadPage from your code
    reloadPage();