| <!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