【问题标题】:javascript countdown timer for session timeout会话超时的javascript倒数计时器
【发布时间】:2012-03-18 03:12:48
【问题描述】:

我想提醒用户会话超时即将到期。我想要一个带有确定按钮的弹出窗口,并在弹出窗口中显示秒数。我可以只用java脚本做到这一点吗? 我也可以在后面使用 C# 代码。

现在它检测到会话超时并弹出告诉他们会话已过期。

<script type="text/javascript">
    var sessionTimeout = "<%= Session.Timeout %>";

    function DisplaySessionTimeout() {
        sessionTimeout = sessionTimeout - 1;

        if (sessionTimeout >= 0)
          window.setTimeout("DisplaySessionTimeout()", 60000);
        else {
            alert("Your current Session is over due to inactivity.");
        }
    }
</script>

【问题讨论】:

  • 此脚本是否仅在用户单击应用程序上的任何内容时才有效,还是会像银行网站一样自动检测超时?

标签: c# javascript asp.net


【解决方案1】:

我发现这个解决方案非常有用。您需要在项目的 web.config 文件中设置身份验证超时以支持此功能,但我还添加了用户可以根据需要继续会话的选项。

将以下内容添加到您的主 HTML 页面 在头部标签中:

<style type="text/css">
#timeOutWarningOverlay {
    position: fixed;
    display: none;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0,0,0,0.5);
    z-index: 2000;
    cursor: pointer;
}
</style>

就在body标签的开头

<div id="timeOutWarningOverlay">
    <div style="height:auto; width:400px; background-color:white; position: fixed;top: 50%;left: 50%; -webkit-transform: translate(-50%, -50%);transform: translate(-50%, -50%);padding:10px; text-align:center;"> 
        <div>
            <b>Your session is about to expire. Please click button below to keep this session current.</b>
            <b><span style="background-color:yellow;">00:</span><span id="time" style="background-color:yellow;">59</span></b>
        </div>
        <a id="keep" href="#">Keep Me Logged In</a>
    </div>
</div> 

现在 JavaScript 来处理这个。我喜欢使用 Jquery,所以这主要是在 Jquery 中,但您可以从该方法中获得想法。此示例适用于 15 分钟超时。请记住,您需要更新您的 web.config 文件身份验证超时。

    var counter = 60;
    var idleTime = 0;
    var countdown;
    $(document).ready(function () {

        $(window).click(function () {
            console.log("click has occured");
            idleTime = 0;
        })
        $(window).keyup(function () {
            console.log("key up has occured")
            idleTime = 0;
        })

        //Increment the idle time counter every minute.
        var idleInterval = setInterval(timerIncrement, 60000); //found

        $('#keep').click(function () {
            idleTime = 0;
            $('#timeOutWarningOverlay').hide();
        });

    });

    function timerIncrement() {
        idleTime = idleTime + 1;
        console.log(idleTime);
        if (idleTime > 13) //13
        {
            $('#timeOutWarningOverlay').show();
            startTimer();
        }
        if (idleTime > 14) { // 14 
            window.location.href = '/login.aspx';
            alert("You session has expired due to no activity.");
        }
    };


    function startTimer() {
        countdown = setInterval(countDownClock, 1000);
    };

    function countDownClock() {
        counter = counter - 1
        if (counter < 10) {
            console.log(counter);
            $('#time').text("0" + counter);
        }
        else {
            console.log(counter);
            $('#time').text(counter);
        }
        if (counter == 0) {
            counter = 60;
            clearInterval(countdown);
            console.log(counter);
            console.log("done");
        }
    };

消息将在 14 分钟后弹出,并开始为用户倒计时。希望这会有所帮助,快乐的编码。

【讨论】:

  • 真的很有帮助...让我的一天变得轻松。我还添加了光标移动功能。效果很好。谢谢你的主意。干杯!!!!!!
【解决方案2】:

是的,您可以通过 JavaScript 执行此操作。这是我不久前发现的一个简单的计数器实现that was inspired from this StackOverflow answer

function Counter(options) {
    var timer;
    var instance = this;
    var seconds = options.seconds || 10;
    var onUpdateStatus = options.onUpdateStatus || function() {};
    var onCounterEnd = options.onCounterEnd || function() {};
    var onCounterStart = options.onCounterStart || function() {};

    function decrementCounter() {
        onUpdateStatus(seconds);
        if (seconds === 0) {
            stopCounter();
            onCounterEnd();
            return;
        }
        seconds--;
    };

    function startCounter() {
        onCounterStart();
        clearInterval(timer);
        timer = 0;
        decrementCounter();
        timer = setInterval(decrementCounter, 1000);
    };

    function stopCounter() {
        clearInterval(timer);
    };

    return {
        start : function() {
            startCounter();
        },
        stop : function() {
            stopCounter();
        }
    }
};

...以及如何使用它的示例:

var countdown = new Counter({
    // number of seconds to count down
    seconds: 3,

    onCounterStart: function () { 
        // show pop up with a message 
        ... 
    },

    // callback function for each second
    onUpdateStatus: function(second) {
        // change the UI that displays the seconds remaining in the timeout 
        ... 
    },

    // callback function for final action after countdown
    onCounterEnd: function() {
        // show message that session is over, perhaps redirect or log out 
        ... 
    }
});
countdown.start();

一旦服务器准备好提醒用户,只需创建计时器,它就会开始倒计时。您可以自定义每个事件发生的情况:计时器何时开始、何时经过以及何时完成倒计时。

【讨论】:

    【解决方案3】:

    我建议使用 setInterval 而不是 setTimeout。

    类似这样的:

    <script>
    var startTime = new Date(milliseconds),
        timeoutLength = 60000;
    
    var interval = setInterval("checkTimeout()",1000);
    function checkTimeout() {
        var currentTime = new Date(millisecond);
        if (currentTime > startTime + timeoutLength) {
            clearInterval(interval);
            alert ("Your current Session is over due to inactivity.");
        }
    }
    </script>
    

    【讨论】:

    • 我需要从页面加载中调用这个函数来触发它吗?如果有,怎么做?
    • 能否请您添加一些关于在何处添加以及它是如何工作的信息。 milliseconds 抛出异常。
    【解决方案4】:

    解决方案 1 - 倒数计时器

    首先只是简单的制作倒数计时器,代码如下,如果你完成了,那么简单的添加 windows.location 路径(重定向页面地址)。

     <sctipt>
            var interval;
             $(document).on('mousemove', function () {
                 clearInterval(interval);
                 var coutdown = 5 * 60, $timer = $('.timer'); // After 5 minutes session expired  (mouse button click code)
                 $timer.text(coutdown);
                 interval = setInterval(function () {
                     $timer.text(--coutdown);
    
                     if (coutdown === 0) {
    
                         alert("Session expired User successfully logout.");
                         window.location = "UserLogin.aspx";
                     }
    
                 }, 1000);
             }).mousemove();
    
    
    
             var interval;
                         $(document).on('keydown', function () {
                 clearInterval(interval);
                 var coutdown = 5 * 60, $timer = $('.timer'); // After 5 minutes session expired (keyboard button press code)
                 $timer.text(coutdown);
                 interval = setInterval(function () {
                     $timer.text(--coutdown);
    
                     if (coutdown === 0) {
    
                         alert("Session expired User successfully logout.");
                         window.location = "UserLogin.aspx";
                     }
    
                 }, 1000);
             }).mousemove();
        <sctipt>
    

    如果您想在网页上显示时间,请添加此代码。

       <html>
             <div class="timer">     
              <p> Session Time</p> 
             </div>
        </html>
    

    解决方案 2 - 使用按钮倒计时

    HTML:

    <script type="text/javascript" src="https://code.jquery.com/jquery-1.7.2.min.js"></script>
            <div class="timer">
                <span class="hour">00</span>:<span class="minute">00</span>:<span class="second">10</span>
            </div>
            <div class="control">
                <button onClick="timer.start(1000)">Start</button> 
                <button onClick="timer.stop()">Stop</button> 
                <button onClick="timer.reset(60)">Reset</button> 
                <button onClick="timer.mode(1)">Count up</button> 
                <button onClick="timer.mode(0)">Count down</button>
            </div>
    

    CSS:

    div.timer {
        border:1px #666666 solid;
        width:190px;
        height:50px;
        line-height:50px;
        font-size:36px;
        font-family:"Courier New", Courier, monospace;
        text-align:center;
        margin:5px;
    }
    

    Javascript:

    function _timer(callback)
    {
        var time = 0;     //  The default time of the timer
        var mode = 1;     //    Mode: count up or count down
        var status = 0;    //    Status: timer is running or stoped
        var timer_id;    //    This is used by setInterval function
    
        // this will start the timer ex. start the timer with 1 second interval timer.start(1000) 
        this.start = function(interval)
        {
            interval = (typeof(interval) !== 'undefined') ? interval : 1000;
    
            if(status == 0)
            {
                status = 1;
                timer_id = setInterval(function()
                {
                    switch(mode)
                    {
                        default:
                        if(time)
                        {
                            time--;
                            generateTime();
                            if(typeof(callback) === 'function') callback(time);
                        }
                        break;
    
                        case 1:
                        if(time < 86400)
                        {
                            time++;
                            generateTime();
                            if(typeof(callback) === 'function') callback(time);
                        }
                        break;
                    }
                }, interval);
            }
        }
    
        //  Same as the name, this will stop or pause the timer ex. timer.stop()
        this.stop =  function()
        {
            if(status == 1)
            {
                status = 0;
                clearInterval(timer_id);
            }
        }
    
        // Reset the timer to zero or reset it to your own custom time ex. reset to zero second timer.reset(0)
        this.reset =  function(sec)
        {
            sec = (typeof(sec) !== 'undefined') ? sec : 0;
            time = sec;
            generateTime(time);
        }
    
        // Change the mode of the timer, count-up (1) or countdown (0)
        this.mode = function(tmode)
        {
            mode = tmode;
        }
    
        // This methode return the current value of the timer
        this.getTime = function()
        {
            return time;
        }
    
        // This methode return the current mode of the timer count-up (1) or countdown (0)
        this.getMode = function()
        {
            return mode;
        }
    
        // This methode return the status of the timer running (1) or stoped (1)
        this.getStatus
        {
            return status;
        }
    
        // This methode will render the time variable to hour:minute:second format
        function generateTime()
        {
            var second = time % 60;
            var minute = Math.floor(time / 60) % 60;
            var hour = Math.floor(time / 3600) % 60;
    
            second = (second < 10) ? '0'+second : second;
            minute = (minute < 10) ? '0'+minute : minute;
            hour = (hour < 10) ? '0'+hour : hour;
    
            $('div.timer span.second').html(second);
            $('div.timer span.minute').html(minute);
            $('div.timer span.hour').html(hour);
        }
    }
    
    // example use
    var timer;
    
    $(document).ready(function(e) 
    {
        timer = new _timer
        (
            function(time)
            {
                if(time == 0)
                {
                    timer.stop();
                    alert('time out');
                }
            }
        );
        timer.reset(0);
        timer.mode(0);
    });
    

    【讨论】:

    • 请尽量在您的解释中更具描述性
    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2014-03-02
    相关资源
    最近更新 更多