Skip to content

Instantly share code, notes, and snippets.

@tophtucker
Last active May 12, 2016 03:45
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 tophtucker/74c273f71d3883751203 to your computer and use it in GitHub Desktop.
Save tophtucker/74c273f71d3883751203 to your computer and use it in GitHub Desktop.
Timer control
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
<button class="play">Play</button>
<button class="pause">Pause</button>
<button class="reset">Reset</button>
</body>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script>
var time = d3.select('body').append('h1');
var timeTimer = new TimerControl(function(t) { time.text(t); });
d3.select('.play').on('click', timeTimer.play);
d3.select('.pause').on('click', timeTimer.pause);
d3.select('.reset').on('click', timeTimer.reset);
// `fn` will be called with context `context` if supplied (optional)
function TimerControl(fn, context) {
var epoch = 0;
var running = false;
// initialize, effectively
fn.call(context || this, epoch);
this.play = function() {
if(running) return;
running = true;
d3.timer(function(t) {
fn.call(context || this, epoch + t);
if (!running) {
epoch += t;
return true;
}
return false;
})
}
this.pause = function() {
running = false;
}
this.reset = function() {
epoch = 0;
fn.call(context || this, epoch);
}
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment