在调用 JavaScript 函数之前清除标签,该函数通过相同的函数 [Session Timeout] 显示计时器

Clear the label before calling a JavaScript function which displays timer through the same function [Session Timeout]

我尝试使用以下函数在网页上的标签(标签 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; 声明移到函数外部,看看它是否有效。

已更新[工作]:

/* Timer - Display Session Timeout */
var x = 0;
function startTimer() {        
    var countDownDate = (new Date().getTime()) + ((parseInt(@SessionTimer)) * 60000);
    clearInterval(x);
    x = setInterval(function () {
        var now = new Date().getTime();
        var distance = countDownDate - now;
        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);
        function checkTime(i) {
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        }
        hours = checkTime(hours);
        minutes = checkTime(minutes);
        seconds = checkTime(seconds);
        document.getElementById("MsgTimer").innerHTML = "Session Expires In" + " " + hours + " : " + minutes + " : " + seconds + "";
        if (distance < 0) {
            clearInterval(x);
            document.getElementById("MsgTimer").innerHTML = "SESSION EXPIRED";
            window.alert("Session Timeout");
        }
    }, 1000);
}
startTimer();    

备选方案[JQuery]:

/* Show 15 Minutes Timer */
var timer2 = "15:01";
var interval = setInterval(function () {
    var timer = timer2.split(':');
    //by parsing integer, I avoid all extra string processing
    var minutes = parseInt(timer[0], 10);
    var seconds = parseInt(timer[1], 10);
    --seconds;
    minutes = (seconds < 0) ? --minutes : minutes;
    if (minutes < 0) clearInterval(interval);
    seconds = (seconds < 0) ? 59 : seconds;
    seconds = (seconds < 10) ? '0' + seconds : seconds;
    //minutes = (minutes < 10) ?  minutes : minutes;
    $('.countdown').html('Session Expires In' + ' ' + minutes + ':' + seconds);
    timer2 = minutes + ':' + seconds;
}, 1000);