Skip to content

Instantly share code, notes, and snippets.

@evsar3
Last active June 26, 2017 20:14
Show Gist options
  • Save evsar3/da7ea74e775f12bd553e104ecc25d5d4 to your computer and use it in GitHub Desktop.
Save evsar3/da7ea74e775f12bd553e104ecc25d5d4 to your computer and use it in GitHub Desktop.
Javascript Timer class | Javascript setInterval extension

Javascript Timer Class

Constructing

// Basic
var timer = new Timer(1000, function () {
    console.log("Tick Tac!");
});

// Call the callback imediatelly
var timer = new Timer(1000, function () {
    console.log("Tick Tac!");
}).execute();

The property count holds the count of how many times the callback was trigged

console.log(timer.count);

Property isRunning holds whether the timer is running or not

console.log(timer.count);

stop, start and restart methods

// Stop the timer. If pass argument 'true' it will reset the counter
timer.stop();
timer.stop(true);

// Start the timer
timer.start();

// Restart the timer. Same as timer.stop(true).start()
timer.restart();

execute will call the timer callback. It accepts an boolean argument that indicates whether the timer should be restarted or not

// Call the timer callback
timer.execute();

// Call the timer callback and restart the timer count
timer.execute(true);

setInterval and setCallback will set the new values at runtime

// Sets a new interval for the timer
timer.setInterval(2000);

// Sets a new callback for the timer
timer.setCallback(function () {
    console.log("Tac Tick!");
});
// This prototype extends the regular setInterval functionality of javascript.
// @author: Evandro Araújo <evandroprogram@gmail.com>
// v1 Mar, 25th 2017 // v2 Jul, 7th 2017
// Timer object
function Timer(interval, callback) {
this.isRunning = false;
this.interval = interval;
this.callback = callback;
this.count = 1;
this.start();
return this;
}
Timer.prototype.start = function () {
var self = this;
this.timer = setInterval(function () {
self.callback.call(self);
self.count++;
}, this.interval);
this.isRunning = true;
return this;
}
Timer.prototype.stop = function (countReset) {
countReset = countReset || false;
clearInterval(this.timer);
this.isRunning = false;
if (countReset) this.count = 1;
return this;
}
Timer.prototype.restart = function () {
this.stop(true).start();
return this;
}
Timer.prototype.execute = function (reset) {
reset = reset || false;
this.callback();
if (reset) this.restart();
return this;
}
Timer.prototype.setInterval = function (interval) {
this.interval = interval;
this.restart();
return this;
}
Timer.prototype.setCallback = function (callback) {
this.callback = callback;
this.restart();
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment