Created
August 9, 2012 20:36
-
-
Save teaforthecat/3307848 to your computer and use it in GitHub Desktop.
javascript timing mechanism to allow multiple machines to sync to the same time, within 50 milliseconds
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
class PollStation | |
start: => @runner = setInterval @oneSecond, 50 | |
stop: => clearInterval(@runner) | |
runner: undefined | |
doOn: (num, func, args) => | |
$(document).on 'poll:oneSecond', (e, second, epochSecond) -> | |
if (epochSecond % num) == 0 | |
$(document.body).trigger("poll:#{num}Second") | |
func() | |
oneSecond: => | |
d = new Date(); | |
epochSecond = (d) -> | |
return Math.floor(d.getTime() / 1000) | |
if d.getMilliseconds() < 50 | |
$(document.body).trigger("poll:oneSecond", [d.getSeconds(), epochSecond(d) ]) | |
### | |
// example | |
poll = new PollStation; | |
poll.start(); | |
// every 7 seconds, from the epoch, the function will be called and a poll event will be triggered on document body | |
poll.doOn(7, poll.stop); | |
// do something every second by listening for the event on the document | |
$(document).on "poll:oneSecond", -> | |
console.log 'hi' ; | |
// do something every second by listening for the event on the document | |
$(document).on "poll:7Second", -> | |
console.log 'hi 7' | |
// for debugging in the console: | |
window.stopPoll = poll.stop; | |
### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment