【发布时间】:2020-02-05 09:56:00
【问题描述】:
我尝试使用以下函数在标签中的网页上显示计时器(标签 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();
【问题讨论】:
-
x定义在哪里,clearInterval定义在哪里? -
x在第 5 行定义,并在第 7 行分配了函数setInterval,clearInterval是 javascript 的内置函数,应该清除SetInterval数据。 -
x是在传递给clearInterval(x)之后定义的 -
感谢您的回复,我刚刚尝试了您的建议,但无法解决我的问题。感谢您的帮助。
标签: javascript asp.net-mvc countdowntimer session-timeout timertask