Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@magicalhobo
Created June 8, 2014 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save magicalhobo/1f69867bc101622beea9 to your computer and use it in GitHub Desktop.
Save magicalhobo/1f69867bc101622beea9 to your computer and use it in GitHub Desktop.
Timer class for node.js
var events = require('events');
var util = require('util');
var EventEmitter = events.EventEmitter;
function Timer(delay, count)
{
EventEmitter.call(this);
count = parseInt(count)
if(isNaN(count))
{
count = 1
}
delay = parseFloat(delay);
if(isNaN(delay))
{
throw new Error('Delay must be a positive Number.');
}
var currentCount = 0;
var intervalId = -1;
var running = false;
var self = this;
this.__defineGetter__('currentCount', function()
{
return currentCount;
});
this.__defineGetter__('delay', function()
{
return delay;
});
this.__defineSetter__('delay', function(value)
{
delay = value;
if(running)
{
self.stop();
self.start();
}
});
this.reset = function()
{
self.stop();
currentCount = 0;
}
this.start = function()
{
if(!running)
{
running = true;
clearInterval(intervalId);
intervalId = setInterval(callback, delay);
}
}
this.stop = function()
{
if(running)
{
running = false;
clearInterval(intervalId);
}
}
function callback()
{
currentCount++;
self.emit('timer');
if(currentCount >= count)
{
self.emit('timerComplete');
self.reset();
}
}
}
util.inherits(Timer, EventEmitter);
@magicalhobo
Copy link
Author

Here's how to use it:

//Creates a timer that runs 10 times, every 100ms.
var timer = new Timer(100, 10);
timer.on('timer', function(ev)
{
    console.log('Timer fired ' + timer.currentCount);
}
timer.start();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment