Skip to content

Instantly share code, notes, and snippets.

@romgerman
Last active June 7, 2017 12:31
Show Gist options
  • Select an option

  • Save romgerman/21c7c9a178ee19c61c906cead903809c to your computer and use it in GitHub Desktop.

Select an option

Save romgerman/21c7c9a178ee19c61c906cead903809c to your computer and use it in GitHub Desktop.
function Timer(interval, repeat, callback) {
this.isStopped = true;
this.interval = interval;
this.repeat = repeat;
this.callback = callback;
this.prevTime = null;
this.start = function() {
this.isStopped = false;
}
this.stop = function() {
this.isStopped = true;
this.prevTime = Date.now();
}
this.onTick = function() {
if (this.isStopped)
return;
var curTime = Date.now();
if (curTime - this.prevTime >= this.interval) {
if (this.callback) this.callback();
this.prevTime = curTime;
}
if (!this.repeat)
this.isStopped = true;
}
}
var timer = new Timer(1000, true, function() {
// do stuff
});
timer.start();
API.onUpdate.connect(function() {
timer.onTick();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment