Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@magicalhobo

magicalhobo Jun 8, 2014

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();
Owner

magicalhobo commented Jun 8, 2014

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