Skip to content

Instantly share code, notes, and snippets.

@thischarmingsam8
Created April 23, 2014 21:33
Show Gist options
  • Select an option

  • Save thischarmingsam8/11233223 to your computer and use it in GitHub Desktop.

Select an option

Save thischarmingsam8/11233223 to your computer and use it in GitHub Desktop.
Typescript class for detecting and reacting to page idle state, still needs touch detection etc.
class IdleTimer
{
timer: any;
timeIncrement: number = 1000;
timeMax: number = 10000;
timeIdle: number = 0;
expiryCallback: Function;
awakeCallback: Function;
tickCallback: Function;
interactionMethods: string[];
expired: boolean = false;
constructor()
{
if ("ontouchstart" in document.documentElement) { console.log('yep!') };
this.interactionMethods = ['click', 'mousemove'];
}
start()
{
this.timeIdle = 0;
this.timer = setInterval(() => this.checkIdleTime(), this.timeIncrement);
for (var i = 0; i < this.interactionMethods.length; i++)
{
document.addEventListener(this.interactionMethods[i], () => this.resetTimer());
}
}
stop()
{
clearInterval(this.timer);
for (var i = 0; i < this.interactionMethods.length; i++) {
document.removeEventListener(this.interactionMethods[i], () => this.resetTimer());
}
}
checkIdleTime ()
{
this.timeIdle += this.timeIncrement;
if (this.timeIdle <= this.timeMax && typeof (this.tickCallback) === 'function') this.tickCallback(this.timeIdle, this.timeMax);
if (this.expired === false && this.timeIdle > this.timeMax)
{
this.expired = true;
if (typeof (this.expiryCallback) === 'function') this.expiryCallback();
}
}
resetTimer()
{
if (this.expired === true)
{
this.expired = false;
if (typeof (this.awakeCallback) === 'function') this.awakeCallback();
}
this.timeIdle = 0;
}
}
//example usage - in main js file
window.onload = function()
{
var it = new IdleTimer();
it.awakeCallback = function(){
document.getElementById('status').innerHTML = "night-time...";
document.getElementById('bird').setAttribute('class','asleep');
};
it.expiryCallback = function(){
document.getElementById('status').innerHTML = "daytime!";
document.getElementById('bird').setAttribute('class','');
};
/*it.tickCallback = function(time, maxtime){
document.getElementById('status').innerHTML = ((maxtime - time)/1000) + '...';
} */
it.start();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment