Javascript:SetTimeout和ClearTimeout重置.
作者:互联网
我有以下会话时间的javascript代码
<script type="text/javascript">
var time;
var sessionTimeout = <%= Session.Timeout %>
function DisplaySessionTimeout() {
document.getElementById("<%= lblSessionTime.ClientID %>").innerText = sessionTimeout;
sessionTimeout = sessionTimeout - 1;
if (sessionTimeout >= 0)
time = window.setTimeout("DisplaySessionTimeout()", 1000);
else {
alert("Your current Session is over.");
}
}
function cleartime() {
clearTimeout(time);
document.onmousemove = cleartime;
document.onkeypress = cleartime;
}
</script>
它可以倒计时.但是当我移动鼠标或按键时没有任何事情发生.我想让它在mousemove和keypress上重置计数器.谁能发现错误?
解决方法:
如果你打算将计时器重置为初始值,那么你就错了.我还建议使用setInterval而不是setTimeout(并传递函数而不是字符串):
var time,
sessionTimeout = <%= Session.Timeout %>,
remainingTime = sessionTimeout,
intervalHandle,
lastPos = [0, 0];
function displaySessionTimeout() {
document.getElementById("<%= lblSessionTime.ClientID %>").innerText = remainingTime;
}
function updateTimer() {
remainingTime -= 1;
if (remainingTime >= 0) {
displaySessionTimeout();
} else {
clearInterval(intervalHandle);
alert("Your current Session is over.");
}
}
function resetTimer() {
if (remainingTime >= 0 && (e.clientX !== lastPos[0] || e.clientY !== lastPos[1])) {
lastPos = [e.clientX, e.clientY];
remainingTime = sessionTimeout;
displaySessionTimeout();
}
}
intervalHandle = setInterval(updateTimer, 1000);
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
displaySessionTimeout();
标签:javascript,asp-net,settimeout,cleartimeout 来源: https://codeday.me/bug/20190830/1771734.html