Countdown timer in javascript

Here i introduce with the simple countdown timer script written in JavaScript. My main purpose behind this countdown timer script is just logout the user if he/she is idle. In this example i set the idle time 15 minutes, means the user will automatically logout if he/she do not active on the page. To achieve this i used window.setInterval() javascript function, which is call my own defined function after every 1 second. As you see in the below example i have created a function getIdleTime(), this function calculate every minute and second and display to the user, as you see i called an id with document.getElementById(), just call the id where you want to show your countdown timer.

I have created a blank div with the id SetIdleTime.

<div id="SetIdleTime"></div>

 

Your countdown timer display the result with this div. To make the page active i have used document.addEventListener() and set three events mousemove, click and keypress and detected the active user through these three events. Please be free leave a comment about this post.

Here is the countdown timer script:

var _imin, _isec, _MIN = 0, IDLE_TIME = 0;

_imin = 15; // IDLE time in minutes
_isec = 60;

// On Mouse Move
document.addEventListener('mousemove', function(){
_MIN = 0;
IDLE_TIME = 0;
});

// On Click
document.addEventListener('click', function(){
_MIN = 0;
IDLE_TIME = 0;
});

// On Key Press
document.addEventListener('keypress', function(){
_MIN = 0;
IDLE_TIME = 0;
});

window.setInterval('getIdleTime()', 1000);

function getIdleTime(){
var _minute, _sec, _nmin, _nsec;

IDLE_TIME++;

if( (_isec - IDLE_TIME) == 0 ){
_MIN++;
IDLE_TIME = 0;
}

_minute = _imin - _MIN;
_sec = _isec - IDLE_TIME;

_nmin = (_minute.toString().length == 1) ? '0' + _minute : _minute;
_nsec = (_sec.toString().length == 1) ? '0' + _sec : _sec;

document.getElementById('SetIdleTime').innerHTML = _nmin + ':' + _nsec;

// Now Redirect Page
// After complete the time

if( _minute == 0 && _sec == 0 ){
alert('Timeout!');
document.location.href = 'logout.html';
}

}