Last active
December 24, 2015 02:09
-
-
Save michalstocki/6728452 to your computer and use it in GitHub Desktop.
Simple 'setTimeout' wrapper which acts as player
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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