Skip to content

Instantly share code, notes, and snippets.

@teaforthecat
Created August 9, 2012 20:36
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 teaforthecat/3307848 to your computer and use it in GitHub Desktop.
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
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