javascript - 在调用通过同一函数 [ session 超时] 显示计时器的 JavaScript 函数之前清除标签

标签 javascript asp.net-mvc countdowntimer session-timeout timertask

我尝试使用以下函数在网页上的标签(标签 id 为 MsgTimer)中显示计时器。但是,当该函数被调用 2/更多次时,将显示 2/更多的计时器,并且它不会重置计时器但会重载标签文本并在标签上显示多个计时器。我想在每次调用该函数时重置标签文本。

function startTimer() {
    var x;
    clearInterval(x);
    document.getElementById("MsgTimer").innerHTML = "";
    // Here I was supposed to fetch the SessionTimeout data from appsettings.json 
    // But for now I entered data manually for 15 minutes
    var countDownDate = new Date().getTime() + 900000;
    // Update the count down every 1 second              
    x = setInterval(function () {        
        // Get todays date and time
        var now = new Date().getTime();
        // Find the distance between now and the count down date
        var distance = countDownDate - now;
        // Time calculations for days, hours, minutes and seconds
        var hours = Math.floor(distance / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // add a zero in front of numbers<10
        function checkTime(i) {
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        }
        hours = checkTime(hours);
        minutes = checkTime(minutes);
        seconds = checkTime(seconds);


        // Display the result in the element with id="lblTime"
        document.getElementById("MsgTimer").innerHTML = "";
        document.getElementById("MsgTimer").innerHTML = "Session Expires In" + " " + minutes + " : " + seconds + "";

        // If the count down is finished, write some text
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("MsgTimer").innerHTML = "SESSION EXPIRED";
            window.alert("Session Timeout");
        }                     
    }, 1000);
}
startTimer();

最佳答案

您的代码的问题可能是 var x; 声明,因为使用 var 关键字声明的变量实际上是函数范围的。

因此,每次 startTimer(); 被调用时,它只会在函数范围内创建一个新的 x 变量,因此 clearInterval(x ) 无法清除先前的时间间隔,因为它无法从先前的 startTimer(); 调用访问 x 的先前值。

尝试将您的 var x; 声明移到函数外部,看看它是否有效。

关于javascript - 在调用通过同一函数 [ session 超时] 显示计时器的 JavaScript 函数之前清除标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60073161/

相关文章:

javascript - 开发 JavaScript 浏览器应用程序的最佳 Node 包是什么?

java - 如何让搜索栏随着计时器的减少而自动滑动/同步到 CountDownTimer

java - 单击按钮即可结束 CountDownTimer

javascript - 带有十字准线作为工具提示的 d3js 图表 : How to Add 2 lines which intersect at cursor position

javascript - 使用 JavaScript 调整 SWF 的大小

asp.net-mvc - Visual Studio 2017 ASP.NET MVC核心模板中的Bower替换

c# - actionresult 刷新当前页面

asp.net - WCF+ Entity Framework 设计

php - 由 MySQL 数据决定的倒计时器

javascript - 使用哈希将类添加到具有特定 href 的 a 元素