让这些计时器得到控制的最佳方法是什么?

时间:2015-01-08 16:18:18

标签: javascript

我继承了这段代码并且已经玩了很长时间了。我现在第一次通过倒计时工作,但在第一次刷新后我相信我仍然有第二次,也许是第三次计时器运行。我确定我需要实现clearInterval()以保持这个稳定的20分钟计时器,但我只是不确定如何正确地执行此操作。任何帮助将不胜感激。

<script type="text/javascript">
    var DoLogout = 1;
    var WarnMills;
    var TimeoutMills;
    var WarnDurationMills;
    var RedirectURL;
    var _timeLeft;

    function StartTimeout(TimeoutValue, WarnValue, WarnDuration, URLValue) {
        TimeoutMills = TimeoutValue;
        WarnMills = WarnValue;
        WarnDurationMills = WarnDuration;
        RedirectURL = URLValue;
        setTimeout(UserTimeout, TimeoutMills);
        setTimeout(WarnTimeout, WarnMills);
    }

    function UserTimeout() {
        if (DoLogout == 1) {
            top.location.href = RedirectURL;
        }
        else {
            DoLogout = 1;
            setTimeout(UserTimeout, TimeoutMills);
            setTimeout(WarnTimeout, WarnMills);
        }
    }

    function WarnTimeout() {
        _timeLeft = (WarnDurationMills / 1000);
        updateCountDown();
        $find('mdlSessionTimeout').show();
    }

    function updateCountDown() {
        var min = Math.floor(_timeLeft / 60);
        var sec = _timeLeft % 60;
        if (sec < 10)
            sec = "0" + sec;

        document.getElementById("CountDownHolder").innerHTML = min + ":" + sec;

        if (_timeLeft > 0) {
            _timeLeft--;
            setTimeout(updateCountDown, 1000);
        }
        else {


            window.location.replace("AdminLogin.aspx");

        }

        if (_timeLeft < (5 * 60)) {
            $find('mdlSessionTimeout').show();
        }
    }

    function PreserveSession() {
        {
            $.ajax({
            type: "POST",
            url: "SessionKeepAlive.asmx/Check",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            cache: false,
            success: checkAuthenticatedOk,
            error: checkAuthenticatedError
        });

    }        
}

function checkAuthenticatedOk() {
    DoLogout = 0;
    _timeLeft = (20 * 60);
    TimeoutMills = (20 * 60 * 1000);
    $find('mdlSessionTimeout').hide();
}

function checkAuthenticatedError() {
    window.location.replace("AdminLogin.aspx");
}

1 个答案:

答案 0 :(得分:0)

调用StartTimeout时,请确保先清除上一个计时器。

var userTimeoutId, warnTimeoutId;
function StartTimeout(...){
    ...
    clearTimeout(userTimeoutId);
    clearTimeout(warnTimeoutId);
    userTimeoutId = setTimeout(UserTimeout, TimeoutMills);
    warnTimeoutId = setTimeout(WarnTimeout, WarnMills);
}

在userTimeout函数下也写相似的代码。