jquery 倒数计时器 - 按键时重置
jquery Countdown Timer - reset on keypress
我有一个用于注销用户的倒数计时器(用于管理站点)。
当用户按下一个键时,它应该重置计时器,但它不起作用。
我该如何重置计时器?
$(function(){
var perc = 50 // User will be logged out after (minutes)
var count = perc * 60;
// RESET TIMER
$(document).keypress(function(){
var count = perc * 60; // PROBLEM
alert('keypress works');
});
//COUNTDOWN
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count == -1) {
// LOGOUT //
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
seconds %= 60;
minutes %= 60;
document.getElementById("seconds").innerHTML = seconds;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("start_time").innerHTML = inactive;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="menu_countdown"><span id="minutes"></span> : <span id="seconds"></span></div>
var 将其限定为按键闭包
var count = perc * 60; // PROBLEM
您需要删除 var
。
$(document).keypress(function(){
count = perc * 60;
});
我有一个用于注销用户的倒数计时器(用于管理站点)。 当用户按下一个键时,它应该重置计时器,但它不起作用。
我该如何重置计时器?
$(function(){
var perc = 50 // User will be logged out after (minutes)
var count = perc * 60;
// RESET TIMER
$(document).keypress(function(){
var count = perc * 60; // PROBLEM
alert('keypress works');
});
//COUNTDOWN
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count == -1) {
// LOGOUT //
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
seconds %= 60;
minutes %= 60;
document.getElementById("seconds").innerHTML = seconds;
document.getElementById("minutes").innerHTML = minutes;
document.getElementById("start_time").innerHTML = inactive;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="menu_countdown"><span id="minutes"></span> : <span id="seconds"></span></div>
var 将其限定为按键闭包
var count = perc * 60; // PROBLEM
您需要删除 var
。
$(document).keypress(function(){
count = perc * 60;
});