Skip to content

Instantly share code, notes, and snippets.

@michalstocki
Last active December 24, 2015 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michalstocki/6728452 to your computer and use it in GitHub Desktop.
Save michalstocki/6728452 to your computer and use it in GitHub Desktop.
Simple 'setTimeout' wrapper which acts as player
function Timer(callback, delay) {
var timerId, start, remaining = delay, going = false;
var _callback = function() {
callback();
remaining = delay;
going = false;
};
this.wait = function() {
if (!going) return;
clearTimeout(timerId);
remaining -= new Date() - start;
going = false;
};
this.go = function() {
start = new Date();
timerId = setTimeout(_callback, remaining);
going = true;
};
}
// for node.js users:
module.exports = Timer;
// Usage:
var playingEnd = function(){ console.log('ended!') };
var player = new Timer(playingEnd, 5000);
player.go(); // starts counting off
player.pause(); // pauses counting off
player.go(); // resumes counting off
player.go(); // can be called after timeout to restart counting for time given while initialization
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment