我尝试使用以下函数在网页上的标签(标签 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/