I making auto logout system with js. How reset timer when I move mouse or click something ? The timer is showing on html. I tried diffrent methods but it still not working.
<div id="ten-countdown"></div>
countdown( "ten-countdown", 1, 20 );
function countdown( elementName, minutes, seconds )
{
var element, endTime, hours, mins, msLeft, time;
function twoDigits( n )
{
return (n <= 9 ? "0" n : n);
}
function updateTimer()
{
msLeft = endTime - ( new Date);
if ( msLeft < 1000 ) {
window.location.href = 'index.php';
} else {
time = new Date( msLeft );
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours ':' twoDigits( mins ) : mins) ':' twoDigits( time.getUTCSeconds() );
setTimeout( updateTimer, time.getUTCMilliseconds() 500 );
}
}
element = document.getElementById( elementName );
endTime = ( new Date) 1000 * (60*minutes seconds) 500;
updateTimer();
}
CodePudding user response:
endTime = 0;
countdown("ten-countdown", 1, 20);
function countdown(elementName, minutes, seconds) {
var element, hours, mins, msLeft, time;
function twoDigits(n) {
return (n <= 9 ? "0" n : n);
}
function updateTimer() {
msLeft = endTime - ( new Date);
if (msLeft < 1000) {
window.location.href = 'index.php';
} else {
time = new Date(msLeft);
hours = time.getUTCHours();
mins = time.getUTCMinutes();
element.innerHTML = (hours ? hours ':' twoDigits(mins) : mins) ':' twoDigits(time.getUTCSeconds());
setTimeout(updateTimer, time.getUTCMilliseconds() 500);
}
}
element = document.getElementById(elementName);
endTime = ( new Date) 1000 * (60 * minutes seconds) 500;
updateTimer();
}
window.addEventListener('mousemove', e => endTime = ( new Date) 1000 * (60 * 1 20) 500)
<div id="ten-countdown"></div>
The most important thing is the last line. It will reset the endTime
variable to 1 minute and 20 seconds in the future whenever the mouse moves.
Notice also that endTime
is now a global variable, so that the onm ouseMove listener can change it.