|
| 1 | +<!doctype html> |
| 2 | +<html> |
| 3 | +<head> |
| 4 | + <title>PubNub Clock Sync Drift Detection</title> |
| 5 | + <style> |
| 6 | + #latency { |
| 7 | + font-size: 30px; |
| 8 | + font-family: "Helvetica Neue"; |
| 9 | + font-weight: 200; |
| 10 | + color: #eeeee2; |
| 11 | + background: #444; |
| 12 | + padding: 10px; |
| 13 | + border-radius: 500px; |
| 14 | + text-align: center; |
| 15 | + |
| 16 | + -webkit-transition: all 0.1s; |
| 17 | + -moz-transition: all 0.1s; |
| 18 | + -ms-transition: all 0.1s; |
| 19 | + -o-transition: all 0.1s; |
| 20 | + transition: all 0.1s; |
| 21 | + } |
| 22 | + h1 { |
| 23 | + font-family: "Helvetica Neue"; |
| 24 | + text-align: center; |
| 25 | + font-weight: 100; |
| 26 | + } |
| 27 | + </style> |
| 28 | +</head> |
| 29 | +<body> |
| 30 | + |
| 31 | +<!-- Clock Drift --> |
| 32 | +<h1>PubNub Clock Sync Drift Detection</h1> |
| 33 | +<div id=latency>40</div> |
| 34 | +<div id=pubnub></div> |
| 35 | +<h3>Checking drift once per second.</h3> |
| 36 | + |
| 37 | + |
| 38 | +<script src="https://cdn.pubnub.com/pubnub.min.js"></script> |
| 39 | +<script>(function(){ |
| 40 | + |
| 41 | + // Drift Functions |
| 42 | + function now(){ return+new Date } |
| 43 | + function clock_drift(cb) { |
| 44 | + clock_drift.start = now(); |
| 45 | + PUBNUB.time(function(timetoken){ |
| 46 | + var latency = (now() - clock_drift.start) / 2 |
| 47 | + , server_time = (timetoken / 10000) + latency |
| 48 | + , local_time = now() |
| 49 | + , drift = local_time - server_time; |
| 50 | + |
| 51 | + cb(drift); |
| 52 | + }); |
| 53 | + |
| 54 | + if (clock_drift.ival) return; |
| 55 | + clock_drift.ival = setInterval( function(){clock_drift(cb)}, 1000 ); |
| 56 | + } |
| 57 | + |
| 58 | + // This is how you use the code |
| 59 | + // Periodically Get Latency in Miliseconds |
| 60 | + clock_drift(function(latency){ |
| 61 | + var out = PUBNUB.$('latency'); |
| 62 | + out.innerHTML = "Clock Drift Delta: " + latency + "ms"; |
| 63 | + |
| 64 | + // Flash Update |
| 65 | + PUBNUB.css( out, { background : latency > 2000 ? '#f32' : '#5b5' } ); |
| 66 | + setTimeout( function() { |
| 67 | + PUBNUB.css( out, { background : '#444' } ); |
| 68 | + }, 300 ); |
| 69 | + }); |
| 70 | + |
| 71 | + |
| 72 | +})();</script> |
| 73 | +</body> |
| 74 | +</html> |
| 75 | + |
0 commit comments